通用列表不显示在ViewBag
本文关键字:ViewBag 显示 列表 | 更新日期: 2023-09-27 18:18:21
我不能给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>
您可以将其强制转换为如下列表:
var m = (from i in Enumerable.Range(0, 12)
let now = DateTime.Now.AddMonths(i)
select now.ToString("MMMM") + " " + now.Year.ToString()).ToList();
ViewBag.b = m;
然后在你的视图中:
@{
var myList = ViewBag.b as List<string>;
}
<ul>
@foreach (var item in myList)
{
<li>@item</li>
}
</ul>
当您对该值执行foreach时,将动态计算列表中的项。如果这让你感觉更好,你可以在这里添加一个。tolist
var m = (from i in Enumerable.Range(0, 12)
let now = DateTime.Now.AddMonths(i)
select now.ToString("MMMM") + " " + now.Year.ToString()).ToList();