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>
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With