Viewbag RuntimeBinderException:' object'不包含定义 [英] Viewbag RuntimeBinderException: 'object' does not contain a definition
问题描述
如何解决此错误,以通过 ViewBag
将数据传递到视图?
How can solve this error to pass data to the view by ViewBag
?
System.Core.dll中发生了类型'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException'的异常,但未在用户代码中处理
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'
在控制器中
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;
在视图中
@{
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;
在 View
中:
foreach (var item in (IEnumerable<MyCategory>)ViewBag.data )
{
<p>@item.name</p>
}
如果您坚持要使用 dynamic
,则可以查看以下问题:
If you insist about using dynamic
you can take a look at these questions:
Razor中的动态匿名类型导致RuntimeBinderException
这篇关于Viewbag RuntimeBinderException:&#39; object&#39;不包含定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!