Dynamic Anonymous type in Razor causes RuntimeBinderException

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

    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 anonymousDictionary = new RouteValueDictionary(anonymousObject);
            IDictionary anonymousDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(anonymousObject);
            IDictionary 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
    
    @*@foreach (dynamic item in Model)*@
    @foreach (var item in Model)
    {
        
    x=@item.nric, y=@item.count
    }

    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.

提交回复
热议问题