Dynamic Anonymous type in Razor causes RuntimeBinderException
Asked Answered
H

12

161

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.

Screenshot of Error

I realize I can do this with a Tuple, but I would like to understand why the error message occurs.

Homophony answered 25/2, 2011 at 17:10 Comment(0)
A
245

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>
}
Antagonism answered 14/4, 2011 at 23:34 Comment(9)
+1 I was specifically looking for HtmlHelper.AnonymousObjectToHtmlAttributes I knew this absolutely had to baked in already and didn't want to reinvent the wheel with similar handrolled code.Nkvd
What is the performance like on this, compared to simply making a strongly typed backing model?Alexei
@DotNetWise, Why would you use HtmlHelper.AnonymousObjectToHtmlAttributes when you can just do IDictionary<string, object> anonymousDictionary = new RouteDictionary(object)?Ceto
I have tested HtmlHelper.AnonymousObjectToHtmlAttributes and works as expected. Your solution can also work. Use whichever seems easier :)Antagonism
If you want it to be a permanent solution, you could also just override the behavior in your controller, but it requires a few more workarounds, like being able to identify anonymous types and creating the string/object dictionary from the type by yourself. If you do that though, you can override it in: protected override System.Web.Mvc.ViewResult View(string viewName, string masterName, object model)Yetah
@Jeremy Your solution is not working for html5 like attributes i.e. new { data_name = "" } - would be converted to data-name="" (which is the client side expected behavior. On our discussion here, really your solution is better as the intented behavior is to have ViewBag.data_name - a valid C#/razor expression - rather than ViewBag.data-name I have updated the answerAntagonism
This answer helped me, but the other part that got me was that I needed to update the WebViewPage to specify that the model is dynamic. This can be done by modifying the .cshtml inherits to the following: @inherits WebViewPage<dynamic>Orient
What if my .Select uses a pre defined projection? eg: someLinq.Select(preDefinedProjection().ToExpando()) where preDefinedProjection() returns a Expression<Func<SomeType, dynamic>>Durian
Another point that should be added is that if you're working with a property on a Model rather than the Model itself, you may need to cast your property to dynamic I.E. public class Model { public IEnumerable<ExpandoObject> Property { get; set; } and then in your view: @foreach ( dynamic item in Model.Property) @item.anonPropNameMccusker
H
52

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.

Homophony answered 25/2, 2011 at 17:26 Comment(6)
Beat me to it :) I ran into this problem with my Razor Engine (the precursor to the one on razorengine.codeplex.com )Nitrobacteria
This is not really an answer, not saying more about the "accepted answer" !Antagonism
@DotNetWise: It explains why the error ocurrs, which was the question. You also get my upvote for providing a nice workaround :)Huxham
FYI: this answer is now very much out of date - as the author says himself in red at the beginning of the referenced blog postBicuspid
@Bicuspid But the post update doesn't explain how it should work in MVC3+. - I hit the same problem in MVC 4. Any pointers on the currently 'blessed' way of using dynamic?Mannikin
Same problem in MVC 5.2.3!!! The ExpandoObject solution that uses a RouteDataValues object to extract the members with reflection works. It truly is an artificial boundary imposed by something in Razor, as there is precisely nothing stopping this conversion from executing in the very same context that the error occurs.Quite
P
26

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;
}
Pitt answered 29/3, 2013 at 9:29 Comment(3)
It's a better answer. Not sure if like what HtmlHelper does with underscores in the alternative answer.Opiumism
+1 for general purpose answer, this is useful outside of ASP / MVCDirichlet
what about nested dynamic properties? they will continue to be dynamic... eg: `{ foo: "foo", nestedDynamic: { blah: "blah" } }Durian
B
17

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.

Bicuspid answered 6/2, 2013 at 11:49 Comment(3)
@yohal you certainly could - I guess it's personal preference. I prefer to use ViewBag for miscellaneous page data generally unrelated to the page model - maybe related to the template and keep Model as the primary modelBicuspid
BTW you don't have to add @model dynamic, as it is the defaultBrackish
exactly what i needed, implementing the method to convert anon objs to expando objects was taking too much time...... thanks heapsEpineurium
M
5

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.

Marital answered 2/3, 2011 at 5:11 Comment(1)
Awesome little trick :) Don't know if it is any better than just a plain class with a bunch of public properties though, at least in this case.Marlborough
M
4

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. :)

Merca answered 6/9, 2011 at 1:59 Comment(0)
B
2

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.

Brackish answered 4/7, 2013 at 17:31 Comment(0)
N
0

I'm going to do a little bit of stealing from https://mcmap.net/q/151997/-why-can-39-t-i-do-this-dynamic-x-new-expandoobject-foo-12-bar-quot-twelve-quot

If you install-package dynamitey you can do this:

return View(Build<ExpandoObject>.NewObject(RatingName: name, Comment: comment));

And the peasants rejoice.

Nkvd answered 29/7, 2014 at 21:4 Comment(0)
C
0

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>[email protected], [email protected]</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.

Cherenkov answered 27/5, 2015 at 4:23 Comment(0)
Z
0

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;
    }
Zworykin answered 13/7, 2015 at 15:27 Comment(0)
W
0

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;
Webbed answered 9/10, 2018 at 15:32 Comment(0)
C
0

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>
Caroylncarp answered 17/1, 2020 at 21:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.