Viewbag RuntimeBinderException: 'object' does not contain a definition
asp.net, asp.net-mvc, asp.net-mvc-4, c#
Solution
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
Problem
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> } } ```