Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for

Posted by Sheonarayan under Error and Solution on 7/17/2014 | Points: 10 | Views : 5655 | Status : [Administrator] | Replies : 0

Problem

I was getting below error when I was trying to bind the list of dynamic objects (IEnumerable<dynamic>) to the partial view in asp.net mvc 5.

Few forums thread on other website says, its a bug that Microsoft is still looking at in ASP.NET MVC 5.

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'ModelProperty'.

Solution


The solution of this problem is to use ExpandoObject. Here is the code for ToExpando extension method.

public static ExpandoObject ToExpando(this object 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;
}


Write your LINQ code like this and return the IEnumerable<dynamic>.
public static IEnumerable<dynamic> GetLatestCharts(KidsFunda4.Models.KidsFundaDB db, int howMany)
{
int _sectionId = int.Parse(Resources.SiteConfiguration.SectionChart);
dynamic charts = (from ch in db.ChartModels
join img in db.ImageModels
on ch.AutoId equals img.ImageForId
where ch.Active == true && ch.IsPublished == true && ch.IsPublic == true
&& img.SectionId == _sectionId
select new
{
ch.AutoId,
ch.NameOfTheChart,
ch.ViewCount,
ch.CreatedDateTime,
ch.UpdatedDateTime,
ch.UserName,
img.ImagePath
}).OrderByDescending(c => c.AutoId).Take(howMany).AsEnumerable().Select(c => c.ToExpando());
return charts;
}

The view model directives would look like this
@model IEnumerable<dynamic>


Now, loop through items of the IEnumerable collection like this

@foreach (dynamic item in Model)
{
@item.ModelProperty
}


Hope this will help someone.

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com



Responses

(No response found.)

Login to post response