Dynamic Anonymous type in Razor causes RuntimeBinderException

后端 未结 12 934
不思量自难忘°
不思量自难忘° 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 08:17

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

提交回复
热议问题