Viewbag RuntimeBinderException:“对象”不包含定义 [英] Viewbag RuntimeBinderException: 'object' does not contain a definition

查看:1727
本文介绍了Viewbag RuntimeBinderException:“对象”不包含定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ViewBag

如何解决这个错误的数据传递给视图

  

类型'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException的异常出现在System.Core.dll但在用户code没有处理


  
  

更多信息:对象不包含名称

的定义

在控制器

  VAR LINQ =(从C在db.Catogeries
            在db.Articals加入上c.Id等于a.CatogeryId
            选择新的{名= c.Name,标题= a.Title});
ViewBag.data = LINQ;

在View

  @ {
     的foreach(在ViewBag.data VAR项)
     {
          &所述p为H.; @ item.name&下; / P>
     }
}


解决方案

简单的方式来解决这个错误产生的一类,而不是使用匿名对象,并使用强类型的模型。

  VAR LINQ =(从C在db.Catogeries
        在db.Articals加入上c.Id等于a.CatogeryId
        选择新的MyCategory {名= c.Name,标题= a.Title});ViewBag.data = LINQ;

查看

 的foreach(在(IEnumerable的&LT VAR项目; MyCategory>)ViewBag.data)
{
     &所述p为H.; @ item.name&下; / P>
}

如果你坚持关于使用动态你可以看看这些问题:

<一个href=\"http://stackoverflow.com/questions/5120317/dynamic-anonymous-type-in-razor-causes-runtimebinderexception\">Dynamic在剃刀匿名类型会导致RuntimeBinderException

<一个href=\"http://stackoverflow.com/questions/3758612/simplest-way-to-do-dynamic-view-models-in-asp-net-mvc-3\">Simplest的方式在ASP.NET MVC 3 做动态视图模式

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

这篇关于Viewbag RuntimeBinderException:“对象”不包含定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆