Search code examples
dynamicasp.net-mvc-3razoranonymous-types

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.

Screenshot of Error

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


Solution

  • 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>
    }