2011-12-19 59 views
0

我無法泛型列表分配給ViewBag:泛型列表不顯示在ViewBag

var m = from i in Enumerable.Range(0, 12) 
     let now = DateTime.Now.AddMonths(i) 
     select now.ToString("MMMM") + " " + now.Year.ToString(); 

ViewBag.b = m; 

我得到這個當我看到ViewBag值:

System.Linq.Enumerable.WhereSelectEnumerableIterator<int,string> 

回答

4

掉落.ToList你可以將它轉換爲一個列表如下:

​​

然後在您的視圖:

@{ 
    var myList = ViewBag.b as List<string>; 
} 

<ul> 
    @foreach (var item in myList) 
    { 
     <li>@item</li> 
    } 
</ul> 
3

中的項目當你對這個值進行foreach時,列表將被動態計算。如果它讓你感覺更好,雖然,你可以在那裏

var m = (from i in Enumerable.Range(0, 12) 
        let now = DateTime.Now.AddMonths(i) 
        select now.ToString("MMMM") + " " + now.Year.ToString()).ToList();