C# ‘dynamic’ cannot access properties from anonymous types declared in another assembly - dynamic

Code below is working well as long as I have class ClassSameAssembly in same assembly as class Program.
But when I move class ClassSameAssembly to a separate assembly, a RuntimeBinderException (see below) is thrown.
Is it possible to resolve it?
using System;
namespace ConsoleApplication2
{
public static class ClassSameAssembly
{
public static dynamic GetValues()
{
return new
{
Name = "Michael", Age = 20
};
}
}
internal class Program
{
private static void Main(string[] args)
{
var d = ClassSameAssembly.GetValues();
Console.WriteLine("{0} is {1} years old", d.Name, d.Age);
}
}
}
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'Name'
at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at ConsoleApplication2.Program.Main(String[] args) in C:\temp\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 23

I believe the problem is that the anonymous type is generated as internal, so the binder doesn't really "know" about it as such.
Try using ExpandoObject instead:
public static dynamic GetValues()
{
dynamic expando = new ExpandoObject();
expando.Name = "Michael";
expando.Age = 20;
return expando;
}
I know that's somewhat ugly, but it's the best I can think of at the moment... I don't think you can even use an object initializer with it, because while it's strongly typed as ExpandoObject the compiler won't know what to do with "Name" and "Age". You may be able to do this:
dynamic expando = new ExpandoObject()
{
{ "Name", "Michael" },
{ "Age", 20 }
};
return expando;
but that's not much better...
You could potentially write an extension method to convert an anonymous type to an expando with the same contents via reflection. Then you could write:
return new { Name = "Michael", Age = 20 }.ToExpando();
That's pretty horrible though :(

You could use [assembly: InternalsVisibleTo("YourAssemblyName")] to make you assembly internals visible.

I ran into a similair problem and would like to add to Jon Skeets answer that there is another option. The reason I found out was that I realized that many extension methods in Asp MVC3 uses anonymous classes as input to provide html attributes (new {alt="Image alt", style="padding-top: 5px"} =>
Anyway - those functions use the constructor of the RouteValueDictionary class. I tried that myself, and sure enough it works - though only the first level (I used a multi-level structure). SO - in code this would be:
object o = new {
name = "theName",
props = new {
p1 = "prop1",
p2 = "prop2"
}
}
SeparateAssembly.TextFunc(o)
//In SeparateAssembly:
public void TextFunc(Object o) {
var rvd = new RouteValueDictionary(o);
//Does not work:
Console.WriteLine(o.name);
Console.WriteLine(o.props.p1);
//DOES work!
Console.WriteLine(rvd["name"]);
//Does not work
Console.WriteLine(rvd["props"].p1);
Console.WriteLine(rvd["props"]["p1"]);
SO... What is really going on here? A peek inside the RouteValueDictionary reveals this code (values ~= o above):
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))
object obj2 = descriptor.GetValue(values);
//"this.Add" would of course need to be adapted
this.Add(descriptor.Name, obj2);
}
SO - using TypeDescriptor.GetProperties(o) we would be able to get the properties and values despite the anonymous type being constructed as internal in a separate assembly! And of course this would be quite easy to extend to make it recursive. And to make an extension method if you wanted.
Hope this helps!
/Victor

Here is a rudimentary version of an extension method for ToExpandoObject that I'm sure has room for polishing.
public static ExpandoObject ToExpandoObject(this object value)
{
// Throw is a helper in my project, replace with your own check(s)
Throw<ArgumentNullException>.If(value, Predicates.IsNull, "value");
var obj = new ExpandoObject() as IDictionary<string, object>;
foreach (var property in value.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
obj.Add(property.Name, property.GetValue(value, null));
}
return obj as ExpandoObject;
}
[TestCase(1, "str", 10.75, 9.000989, true)]
public void ToExpandoObjectTests(int int1, string str1, decimal dec1, double dbl1, bool bl1)
{
DateTime now = DateTime.Now;
dynamic value = new {Int = int1, String = str1, Decimal = dec1, Double = dbl1, Bool = bl1, Now = now}.ToExpandoObject();
Assert.AreEqual(int1, value.Int);
Assert.AreEqual(str1, value.String);
Assert.AreEqual(dec1, value.Decimal);
Assert.AreEqual(dbl1, value.Double);
Assert.AreEqual(bl1, value.Bool);
Assert.AreEqual(now, value.Now);
}

Below solution worked for me in my console application projects
Put this [assembly: InternalsVisibleTo("YourAssemblyName")]
in \Properties\AssemblyInfo.cs of the separate project with function returning dynamic object.
"YourAssemblyName" is the assembly name of calling project. You can get that through Assembly.GetExecutingAssembly().FullName by executing it in calling project.

A cleaner solution would be:
var d = ClassSameAssembly.GetValues().ToDynamic();
Which is now an ExpandoObject.
Remember to reference:
Microsoft.CSharp.dll

ToExpando extension method (mentioned in Jon's answer) for the brave ones
public static class ExtensionMethods
{
public static ExpandoObject ToExpando(this object obj)
{
IDictionary<string, object> expando = new ExpandoObject();
foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(obj))
{
var value = propertyDescriptor.GetValue(obj);
expando.Add(propertyDescriptor.Name, value == null || new[]
{
typeof (Enum),
typeof (String),
typeof (Char),
typeof (Guid),
typeof (Boolean),
typeof (Byte),
typeof (Int16),
typeof (Int32),
typeof (Int64),
typeof (Single),
typeof (Double),
typeof (Decimal),
typeof (SByte),
typeof (UInt16),
typeof (UInt32),
typeof (UInt64),
typeof (DateTime),
typeof (DateTimeOffset),
typeof (TimeSpan),
}.Any(oo => oo.IsInstanceOfType(value))
? value
: value.ToExpando());
}
return (ExpandoObject)expando;
}
}

If you're already using Newtonsoft.Json in your project (or you're willing to add it for this purpose), you could implement that horrible extension method Jon Skeet is referring to in his answer like this:
public static class ObjectExtensions
{
public static ExpandoObject ToExpando(this object obj)
=> JsonConvert.DeserializeObject<ExpandoObject>(JsonConvert.SerializeObject(obj));
}

Related

How to .Dump() XNode as a regular object with properties in LINQPad?

Normally, the .Dump() extension method in LINQPad shows XNode and its derived class instances as a rendered XML fragment. Sometimes while developing code I would prefer to see actual properties of the object, in the same table form that is dumped for other types, like a table that would show the Name, Value, FirstAttribute and whatsnot properties of the node and their .ToString() values, or interactively expandable collections of subobjects. In short, as if XNode were not handled specially at all.
I am working around this by dumping individual properties, but this is tedious.
This answer suggests writing a custom extension code to achieve a similar effect for another type, namely IEnumerable, but it seems a narrower and rarer case than that which I am dealing with.
Is there an out-of-the box way to do what I want?
LINQPad supports customizing Dump for types. Using some extension methods, you can convert the types to ExpandoObjects and then they will be output with properties.
In My Extensions, after the MyExtensions class, add a top level method:
static object ToDump(object obj) {
if (obj is XObject x)
return x.ToExpando();
else
return obj;
}
In the MyExtensions class, add the following extension methods. I already had the object->Dictionary methods for converting to anonymous objects, so I used those, but you could combine them to create a single ToExpando on object:
public static ExpandoObject ToExpando(this object obj) => obj.ToDictionary().ToExpando();
public static IDictionary<string, object> ToDictionary(this object obj) {
if (obj is IDictionary<string, object> id)
return id;
else {
var dictAnsObj = new Dictionary<string, object>();
foreach (var prop in obj.GetType().GetPropertiesOrFields()) {
try {
dictAnsObj.Add(prop.Name, prop.GetValue(obj));
}
catch (Exception ex) {
dictAnsObj.Add(prop.Name, ex);
}
}
return dictAnsObj;
}
}
public static ExpandoObject ToExpando(this IDictionary<string, object> objDict) {
var e = new ExpandoObject();
var di = (IDictionary<string, object>)e;
foreach (var kvp in objDict)
di.Add(kvp);
return e;
}
You will also need this Type extension:
// ***
// *** Type Extensions
// ***
public static List<MemberInfo> GetPropertiesOrFields(this Type t, BindingFlags bf = BindingFlags.Public | BindingFlags.Instance) =>
t.GetMembers(bf).Where(mi => mi.MemberType == MemberTypes.Field | mi.MemberType == MemberTypes.Property).ToList();
If you are okay with just displaying the top level object in class format, you could just use this extension method when you need to:
public static T DumpAs<T, NewT>(this T obj, Func<T, NewT> castFn, string description = null) {
if (description != null)
castFn(obj).Dump(description);
else
castFn(obj).Dump();
return obj;
}
For example,
XElement xn;
xn.DumpAs(x => x.ToExpando());
Otherwise, you will have to comment out the ToDump method or do something tricky with fluent methods to turn it on and off.
This answer depends on the previous answer, but extends it to handle dumping XObjects as classes when desired with an alternative extension method and ToDump method. It uses the same extensions as my previous answer otherwise.
In the MyExtensions class, add a new type of dump and a bool to track status:
public static bool bDumpAsClass = false;
public static object DumpAsClass(this object input, string descr = null) {
bDumpAsClass = true;
if (descr != null)
input.Dump(descr);
else
input.Dump();
bDumpAsClass = false;
return input;
}
Outside the MyExtensions class, add a ToDump method that uses the bool:
static object ToDump(object obj) {
if (MyExtensions.bDumpAsClass) {
if (obj is XObject x)
return x.ToExpando();
}
return obj;
}
Then you can just use DumpAsClass instead of Dump when you want to dump an XObject or descendant as a class, expanding any members as well.
Obviously you could expand the types handled when bDumpAsClass is true.

Can I apply an aspect to all public methods in an assembly with a specific return type?

I'd like to apply an aspect to all public methods in an assembly who have the return type of ActionResult.
I'm thinking something like:
[assembly: MyActionAspect(AttributeTargetMemberAttributes = MulticastAttributes.Public, AttributeTargetTypes = "ActionResult")]
But it doesn't seem to work...
In your example you set AttributeTargetTypes = "ActionResult", but AttributeTargetTypes is not related to the return type of the method. It allows you to filter types on which to apply the aspect. So, you would set it to the full name of the ActionResult type if you wanted to apply the aspect inside the ActionResult class (you can also use wildcards and regex in this property).
However, to filter methods on return type you need to take a different approach.
The first option is to override CompileTimeValidate in your aspect and return false for methods that you want to filter out:
public override bool CompileTimeValidate(MethodBase method)
{
MethodInfo methodInfo = method as MethodInfo;
return methodInfo != null && methodInfo.ReturnType == typeof (ActionResult);
}
The second option is to create another attribute and implement IAspectProvider. This is a bit more laborious, but allows you to add aspects dynamically to your code and to implement more complex scenarios.
[MulticastAttributeUsage(MulticastTargets.Method)]
public class MyAspectProvider : MulticastAttribute, IAspectProvider
{
public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
{
MethodInfo methodInfo = (MethodInfo) targetElement;
if (methodInfo.ReturnType == typeof (ActionResult))
{
return new[] {new AspectInstance(targetElement, new MyActionAspect())};
}
return new AspectInstance[0];
}
}
// apply to assembly:
[assembly: MyAspectProvider(AttributeTargetMemberAttributes = MulticastAttributes.Public)]
You can read more about IAspectProvider on this doc page.

Can an Dapper query to changed to an ObservableCollection?

I'm tying to learn to use dapper.
I have this class here:
public class Member_Collection : ObservableCollection<Member>
{
}
and I have this method in my DAL class:
public static Member_Collection SqlSelectAll(string connString)
{
Member_Collection entityToReturn = null;
using (var conn = new SqlConnection(connString))
{
var entityList = conn.Query("Select * From Member");
entityToReturn = new Member_Collection();
foreach (var item in entityList)
{
entityToReturn.Add(item);
}
}
return entityToReturn;
}
This there away for the query to return an ObservableCollection?
Getting it to "return" a specific collection type would be a case of adding a custom extension method. If you just wanted the generic observable collection type, then:
public static ObservableCollection<T> ToObservable<T>(
this IEnumerable<T> source)
{
return new ObservableCollection<T>(source);
}
Note that to return a specific subclass is more complicated. To use generics would require the caller to specify both generic arguments, which is vexing. You might need a per-item-type extension method - again, pretty ugly

Mono.CSharp: how do I inject a value/entity *into* a script?

Just came across the latest build of Mono.CSharp and love the promise it offers.
Was able to get the following all worked out:
namespace XAct.Spikes.Duo
{
class Program
{
static void Main(string[] args)
{
CompilerSettings compilerSettings = new CompilerSettings();
compilerSettings.LoadDefaultReferences = true;
Report report = new Report(new Mono.CSharp.ConsoleReportPrinter());
Mono.CSharp.Evaluator e;
e= new Evaluator(compilerSettings, report);
//IMPORTANT:This has to be put before you include references to any assemblies
//our you;ll get a stream of errors:
e.Run("using System;");
//IMPORTANT:You have to reference the assemblies your code references...
//...including this one:
e.Run("using XAct.Spikes.Duo;");
//Go crazy -- although that takes time:
//foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
//{
// e.ReferenceAssembly(assembly);
//}
//More appropriate in most cases:
e.ReferenceAssembly((typeof(A).Assembly));
//Exception due to no semicolon
//e.Run("var a = 1+3");
//Doesn't set anything:
//e.Run("a = 1+3;");
//Works:
//e.ReferenceAssembly(typeof(A).Assembly);
e.Run("var a = 1+3;");
e.Run("A x = new A{Name=\"Joe\"};");
var a = e.Evaluate("a;");
var x = e.Evaluate("x;");
//Not extremely useful:
string check = e.GetVars();
//Note that you have to type it:
Console.WriteLine(((A) x).Name);
e = new Evaluator(compilerSettings, report);
var b = e.Evaluate("a;");
}
}
public class A
{
public string Name { get; set; }
}
}
And that was fun...can create a variable in the script's scope, and export the value.
There's just one last thing to figure out... how can I get a value in (eg, a domain entity that I want to apply a Rule script on), without using a static (am thinking of using this in a web app)?
I've seen the use compiled delegates -- but that was for the previous version of Mono.CSharp, and it doesn't seem to work any longer.
Anybody have a suggestion on how to do this with the current version?
Thanks very much.
References:
* Injecting a variable into the Mono.CSharp.Evaluator (runtime compiling a LINQ query from string)
* http://naveensrinivasan.com/tag/mono/
I know it's almost 9 years later, but I think I found a viable solution to inject local variables. It is using a static variable but can still be used by multiple evaluators without collision.
You can use a static Dictionary<string, object> which holds the reference to be injected. Let's say we are doing all this from within our class CsharpConsole:
public class CsharpConsole {
public static Dictionary<string, object> InjectionRepository {get; set; } = new Dictionary<string, object>();
}
The idea is to temporarily place the value in there with a GUID as key so there won't be any conflict between multiple evaluator instances. To inject do this:
public void InjectLocal(string name, object value, string type=null) {
var id = Guid.NewGuid().ToString();
InjectionRepository[id] = value;
type = type ?? value.GetType().FullName;
// note for generic or nested types value.GetType().FullName won't return a compilable type string, so you have to set the type parameter manually
var success = _evaluator.Run($"var {name} = ({type})MyNamespace.CsharpConsole.InjectionRepository[\"{id}\"];");
// clean it up to avoid memory leak
InjectionRepository.Remove(id);
}
Also for accessing local variables there is a workaround using Reflection so you can have a nice [] accessor with get and set:
public object this[string variable]
{
get
{
FieldInfo fieldInfo = typeof(Evaluator).GetField("fields", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo != null)
{
var fields = fieldInfo.GetValue(_evaluator) as Dictionary<string, Tuple<FieldSpec, FieldInfo>>;
if (fields != null)
{
if (fields.TryGetValue(variable, out var tuple) && tuple != null)
{
var value = tuple.Item2.GetValue(_evaluator);
return value;
}
}
}
return null;
}
set
{
InjectLocal(variable, value);
}
}
Using this trick, you can even inject delegates and functions that your evaluated code can call from within the script. For instance, I inject a print function which my code can call to ouput something to the gui console window:
public delegate void PrintFunc(params object[] o);
public void puts(params object[] o)
{
// call the OnPrint event to redirect the output to gui console
if (OnPrint!=null)
OnPrint(string.Join("", o.Select(x => (x ?? "null").ToString() + "\n").ToArray()));
}
This puts function can now be easily injected like this:
InjectLocal("puts", (PrintFunc)puts, "CsInterpreter2.PrintFunc");
And just be called from within your scripts:
puts(new object[] { "hello", "world!" });
Note, there is also a native function print but it directly writes to STDOUT and redirecting individual output from multiple console windows is not possible.

Dynamic Anonymous type in Razor causes RuntimeBinderException

I'm getting the following error:
'object' does not contain a definition for 'RatingName'
When you look at the anonymous dynamic type, it clearly does have RatingName.
I realize I can do this with a Tuple, but I would like to understand why the error message occurs.
Anonymous types having internal properties is a poor .NET framework design decision, in my opinion.
Here is a quick and nice extension to fix this problem i.e. by converting the anonymous object into an ExpandoObject right away.
public static ExpandoObject ToExpando(this object anonymousObject)
{
IDictionary<string, object> anonymousDictionary = new RouteValueDictionary(anonymousObject);
IDictionary<string, object> expando = new ExpandoObject();
foreach (var item in anonymousDictionary)
expando.Add(item);
return (ExpandoObject)expando;
}
It's very easy to use:
return View("ViewName", someLinq.Select(new { x=1, y=2}.ToExpando());
Of course in your view:
#foreach (var item in Model) {
<div>x = #item.x, y = #item.y</div>
}
I found the answer in a related question. The answer is specified on David Ebbo's blog post Passing anonymous objects to MVC views and accessing them using dynamic
The reason for this is that the
anonymous type being passed in the
controller in internal, so it can only
be accessed from within the assembly
in which it’s declared. Since views
get compiled separately, the dynamic
binder complains that it can’t go over
that assembly boundary.
But if you think about it, this
restriction from the dynamic binder is
actually quite artificial, because if
you use private reflection, nothing is
stopping you from accessing those
internal members (yes, it even work in
Medium trust). So the default dynamic
binder is going out of its way to
enforce C# compilation rules (where
you can’t access internal members),
instead of letting you do what the CLR
runtime allows.
Using ToExpando method is the best solution.
Here is the version that doesn't require System.Web assembly:
public static ExpandoObject ToExpando(this object anonymousObject)
{
IDictionary<string, object> expando = new ExpandoObject();
foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(anonymousObject))
{
var obj = propertyDescriptor.GetValue(anonymousObject);
expando.Add(propertyDescriptor.Name, obj);
}
return (ExpandoObject)expando;
}
Instead of creating a model from an anonymous type and then trying to convert the anonymous object to an ExpandoObject like this ...
var model = new
{
Profile = profile,
Foo = foo
};
return View(model.ToExpando()); // not a framework method (see other answers)
You can just create the ExpandoObject directly:
dynamic model = new ExpandoObject();
model.Profile = profile;
model.Foo = foo;
return View(model);
Then in your view you set the model type as dynamic #model dynamic and you can access the properties directly :
#Model.Profile.Name
#Model.Foo
I'd normally recommend strongly typed view models for most views, but sometimes this flexibility is handy.
You can use the framework impromptu interface to wrap an anonymous type in an interface.
You'd just return an IEnumerable<IMadeUpInterface> and at the end of your Linq use .AllActLike<IMadeUpInterface>(); this works because it calls the anonymous property using the DLR with a context of the assembly that declared the anonymous type.
Wrote a console application and add Mono.Cecil as reference (you can now add it from NuGet), then write the piece of code:
static void Main(string[] args)
{
var asmFile = args[0];
Console.WriteLine("Making anonymous types public for '{0}'.", asmFile);
var asmDef = AssemblyDefinition.ReadAssembly(asmFile, new ReaderParameters
{
ReadSymbols = true
});
var anonymousTypes = asmDef.Modules
.SelectMany(m => m.Types)
.Where(t => t.Name.Contains("<>f__AnonymousType"));
foreach (var type in anonymousTypes)
{
type.IsPublic = true;
}
asmDef.Write(asmFile, new WriterParameters
{
WriteSymbols = true
});
}
The code above would get the assembly file from input args and use Mono.Cecil to change the accessibility from internal to public, and that would resolve the problem.
We can run the program in the Post Build event of the website. I wrote a blog post about this in Chinese but I believe you can just read the code and snapshots. :)
Based on the accepted answer, I have overridden in the controller to make it work in general and behind the scenes.
Here is the code:
protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
base.OnResultExecuting(filterContext);
//This is needed to allow the anonymous type as they are intenal to the assembly, while razor compiles .cshtml files into a seperate assembly
if (ViewData != null && ViewData.Model != null && ViewData.Model.GetType().IsNotPublic)
{
try
{
IDictionary<string, object> expando = new ExpandoObject();
(new RouteValueDictionary(ViewData.Model)).ToList().ForEach(item => expando.Add(item));
ViewData.Model = expando;
}
catch
{
throw new Exception("The model provided is not 'public' and therefore not avaialable to the view, and there was no way of handing it over");
}
}
}
Now you can just pass an anonymous object as the model, and it will work as expected.
I'm going to do a little bit of stealing from https://stackoverflow.com/a/7478600/37055
If you install-package dynamitey you can do this:
return View(Build<ExpandoObject>.NewObject(RatingName: name, Comment: comment));
And the peasants rejoice.
The reason of RuntimeBinderException triggered, I think there have good answer in other posts. I just focus to explain how I actually make it work.
By refer to answer #DotNetWise and Binding views with Anonymous type collection in ASP.NET MVC,
Firstly, Create a static class for extension
public static class impFunctions
{
//converting the anonymous object into an ExpandoObject
public static ExpandoObject ToExpando(this object anonymousObject)
{
//IDictionary<string, object> anonymousDictionary = new RouteValueDictionary(anonymousObject);
IDictionary<string, object> anonymousDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(anonymousObject);
IDictionary<string, object> expando = new ExpandoObject();
foreach (var item in anonymousDictionary)
expando.Add(item);
return (ExpandoObject)expando;
}
}
In controller
public ActionResult VisitCount()
{
dynamic Visitor = db.Visitors
.GroupBy(p => p.NRIC)
.Select(g => new { nric = g.Key, count = g.Count()})
.OrderByDescending(g => g.count)
.AsEnumerable() //important to convert to Enumerable
.Select(c => c.ToExpando()); //convert to ExpandoObject
return View(Visitor);
}
In View, #model IEnumerable (dynamic, not a model class), this is very important as we are going to bind the anonymous type object.
#model IEnumerable<dynamic>
#*#foreach (dynamic item in Model)*#
#foreach (var item in Model)
{
<div>x=#item.nric, y=#item.count</div>
}
The type in foreach, I have no error either using var or dynamic.
By the way, create a new ViewModel that is matching the new fields also can be the way to pass the result to the view.
Now in recursive flavor
public static ExpandoObject ToExpando(this object obj)
{
IDictionary<string, object> expandoObject = new ExpandoObject();
new RouteValueDictionary(obj).ForEach(o => expandoObject.Add(o.Key, o.Value == null || new[]
{
typeof (Enum),
typeof (String),
typeof (Char),
typeof (Guid),
typeof (Boolean),
typeof (Byte),
typeof (Int16),
typeof (Int32),
typeof (Int64),
typeof (Single),
typeof (Double),
typeof (Decimal),
typeof (SByte),
typeof (UInt16),
typeof (UInt32),
typeof (UInt64),
typeof (DateTime),
typeof (DateTimeOffset),
typeof (TimeSpan),
}.Any(oo => oo.IsInstanceOfType(o.Value))
? o.Value
: o.Value.ToExpando()));
return (ExpandoObject) expandoObject;
}
Using the ExpandoObject Extension works but breaks when using nested anonymous objects.
Such as
var projectInfo = new {
Id = proj.Id,
UserName = user.Name
};
var workitem = WorkBL.Get(id);
return View(new
{
Project = projectInfo,
WorkItem = workitem
}.ToExpando());
To accomplish this I use this.
public static class RazorDynamicExtension
{
/// <summary>
/// Dynamic object that we'll utilize to return anonymous type parameters in Views
/// </summary>
public class RazorDynamicObject : DynamicObject
{
internal object Model { get; set; }
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (binder.Name.ToUpper() == "ANONVALUE")
{
result = Model;
return true;
}
else
{
PropertyInfo propInfo = Model.GetType().GetProperty(binder.Name);
if (propInfo == null)
{
throw new InvalidOperationException(binder.Name);
}
object returnObject = propInfo.GetValue(Model, null);
Type modelType = returnObject.GetType();
if (modelType != null
&& !modelType.IsPublic
&& modelType.BaseType == typeof(Object)
&& modelType.DeclaringType == null)
{
result = new RazorDynamicObject() { Model = returnObject };
}
else
{
result = returnObject;
}
return true;
}
}
}
public static RazorDynamicObject ToRazorDynamic(this object anonymousObject)
{
return new RazorDynamicObject() { Model = anonymousObject };
}
}
Usage in the controller is the same except you use ToRazorDynamic() instead of ToExpando().
In your view to get the entire anonymous object you just add ".AnonValue" to the end.
var project = #(Html.Raw(JsonConvert.SerializeObject(Model.Project.AnonValue)));
var projectName = #Model.Project.Name;
I tried the ExpandoObject but it didn't work with a nested anonymous complex type like this:
var model = new { value = 1, child = new { value = 2 } };
So my solution was to return a JObject to View model:
return View(JObject.FromObject(model));
and convert to dynamic in .cshtml:
#using Newtonsoft.Json.Linq;
#model JObject
#{
dynamic model = (dynamic)Model;
}
<span>Value of child is: #model.child.value</span>