我正在从数据库中检索国家的名称和ID,并将其设置在Viewbag中。但是当我从查看它的抛出错误访问它时。

这是C#代码:-

var country = from x in db.Territories select new
                 {
                  x.Name,
                  x.ID
                 };
 ViewBag.countries = country;


查看页面代码:-

@foreach (var item in ViewBag.countries)
{
   <td><label class="control-label">@item.Name</label></td>
}


错误: -

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'Name'

最佳答案

您的代码中有一些错误。


您应该创建CountryModel类,并在操作中选择这些模型的列表,如果使用匿名类型,则无法在视图中使用它。
我建议您不要使用ViewBag传递数据进行查看,最好的方法是使用Model。


模型:

public class CountryModel
{
    public int Id {get;set;}
    public string Name {get;set;}
}


行动:

var countries = (
    from x in db.Territories
    select new CountryModel
       {
          Name = x.Name,
          Id = x.ID
       }).ToList();

return View(countries);


视图:

@model List<CountryModel>
@foreach (var item in Model)
{
   <td><label class="control-label">@item.Name</label></td>
}

10-07 19:00
查看更多