Dynamic Anonymous type in Razor causes RuntimeBinderException

后端 未结 12 1036
不思量自难忘°
不思量自难忘° 2020-11-22 07:45

I\'m getting the following error:

\'object\' does not contain a definition for \'RatingName\'

When you look at the anonymous dyn

12条回答
  •  面向向阳花
    2020-11-22 07:55

    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 anonymousDictionary =  new RouteValueDictionary(anonymousObject);
        IDictionary 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) {
         
    x = @item.x, y = @item.y
    }

提交回复
热议问题