2013-12-17 67 views
2
public ActionResult Index() 
{ 
     var groups = db.SHP_Products 
        .GroupBy(c => c.SHP_Category.Name, 
            (category, items) => new 
            { 
             CategoryName = category, 
             ItemCount = items.Count(), 
             Items = items 
            } 
          ); 
     ViewBag.group = groups.ToList(); 
     return View(); 
} 

的定義,當運行這個它會顯示類似這樣的錯誤:「對象」不包含「類別名稱」

<ul> 
    @foreach (var m in ViewBag.group) 
    { 
     <h2>@m.CategoryName</h2> 
     <a href="#" class="prev1">Previous</a><a href="#" class="next1">Next</a> 
     <li></li> 
    } 
</ul> 

'object' does not contain a definition for 'CategoryName' 

回答

0

我認爲你正試圖直接訪問<h2>@m.CategoryName</h2>看看,可能是你可以像@m.SHP_Category.Name訪問它,我真的不知道你在你的代碼的類的序列。嘗試@m.

0

From

這樣做的原因是,在內部控制器傳遞的匿名類型,所以它只能從在其中它被聲明在組件內訪問。由於視圖是單獨編譯的,因此動態聯編程序會抱怨它無法遍歷該程序集邊界。

解決此問題的一種方法是使用System.Dynamic.ExpandoObject

public static ExpandoObject ToExpando(this object obj) 
    { 
     IDictionary<string, object> expandoObject = new ExpandoObject(); 
     new RouteValueDictionary(obj).ForEach(o => expandoObject.Add(o.Key, o.Value)); 

     return (ExpandoObject) expandoObject; 
    } 

然後:

ToExpando(groups); // might need toList() it too. 
0

請使用ViewData的,而不是ViewBag喜歡這裏。

控制器:

public ActionResult Index() 
{ 
    var groups = db.SHP_Products 
       .GroupBy(c => c.SHP_Category.Name, 
           (category, items) => new 
           { 
            CategoryName = category, 
            ItemCount = items.Count(), 
            Items = items 
           } 
         ); 
    ViewData["groups"] = groups.ToList(); 
    return View(); 
} 

查看:

<ul> 
@foreach (var m in (dynamic) ViewData["groups"]) 
{ 
    <h2>@m.CategoryName</h2> 
    <a href="#" class="prev1">Previous</a><a href="#" class="next1">Next</a> 
    <li></li> 
}