2014-03-07 39 views
3

我從數據庫中檢索國家的名稱和ID並將其設置在Viewbag中。但是,當我從視圖訪問它的投擲錯誤。無法從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' 

回答

2

你在你的代碼中的一些錯誤。

  1. 您應該創建CountryModel類,並在你的行動選擇這些車型的名單,在使用你不能在視圖中使用它anonymus類型的情況。
  2. 我建議你不要用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>  
} 
+0

謝謝你..它的工作。:) – user3206357

0

的ViewBag不是強類型,所以MVC沒有按不知道你的itemCountry,只把它看作一個對象。

試試這個:

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

如果我米使用你的代碼,然後收到此錯誤: - 無法施展的對象鍵入'<> f__AnonymousType1f'2 [System.String,System.Int64]'鍵入'Assetry.Model.Country'。 – user3206357

+0

你的代碼是錯誤的,你應該將ViewBag.countries轉換爲IEnumerable ,而不是item。 – alexmac

+0

好的..謝謝你.. – user3206357