Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Viewbag RuntimeBinderException: 'object' does not contain a definition

How can solve this error to pass data to the view by ViewBag?

An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code

Additional information: 'object' does not contain a definition for 'name'

In Controller

var linq = (from c in db.Catogeries
            join a in db.Articals on c.Id equals a.CatogeryId
            select new  {name=c.Name,title=a.Title });
ViewBag.data = linq;
       

In View

@{         
     foreach (var item in ViewBag.data )
     {
          <p>@item.name</p>
     }
}
like image 842
user3234114 Avatar asked Feb 23 '14 00:02

user3234114


Video Answer


1 Answers

The simplest way to fix this error creating a class instead of using anonymous object and use strongly-typed model.

var linq = (from c in db.Catogeries
        join a in db.Articals on c.Id equals a.CatogeryId
        select new MyCategory { name=c.Name, title=a.Title });

ViewBag.data = linq;

In View:

foreach (var item in (IEnumerable<MyCategory>)ViewBag.data )
{
     <p>@item.name</p>
}

If you insist about using dynamic you can take a look at these questions:

Dynamic Anonymous type in Razor causes RuntimeBinderException

Simplest Way To Do Dynamic View Models in ASP.NET MVC 3

like image 189
Selman Genç Avatar answered Sep 20 '22 21:09

Selman Genç