Reputation: 107
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>
}
}
Upvotes: 8
Views: 29808
Reputation: 31
here is how I resolved my issue and I hope this may help someone:
I created a Class:
public class MyClass
{
public decimal EmployeeId { get; set; }
public string CategoryCode { get; set; }
public string CategoryDesc { get; set; }
}
}
At the Controller:
var query = (from c in context.EmployeeCategory
where(c.EMPLOYEE_ID == 22)
join a in context.Categories on c.Category_CODE
equals a.Category_CODE
select new MyClass
{
EmployeeId = c.EMPLOYEE_ID,
CategoryCode = a.Category_CODE,
CategoryDesc = a.Category_DESC
});
return View(query);
At the View:
@model IEnumerable<MyClass>
@foreach (var item in Model)
{
@item.EmployeeId <b> - </b>
@item.CategoryCode <br />
@item.CategoryDesc <br />
}
Upvotes: 3
Reputation: 24280
The problem is actually caused by setting the Viewbag
value. In the process .NET always throws an internal Exception, and then Visual Studio breaks into the debugger.
Solution: make Visual Studio break only for exceptions in your own code. Go to menu Tools/Options, select Debugging on the left, and check [v] the option "Enable Just My Code".
Upvotes: 2
Reputation: 101731
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
Upvotes: 7
Reputation: 101614
You just need to cast it. The view doesn't have any idea what type the object is so trying to enumerate it won't work until you cast it. Something like:
foreach (var item in (IEnumerable <dynamic>) ViewBag.data) { ... }
Sorry if format is off slightly, trying to do this on phone.
Upvotes: -2