问题描述
我需要使用 viewbag 显示数据列表.但我无法做到.
请帮我..
我试过这个:
Hi i need to show a list of data using viewbag.but i am not able to do it.
Please Help me..
I tried this thing:
ICollection<Learner> list = new HobbyHomeService().FetchLearner();
ICollection<Person> personlist = new HobbyHomeService().FetchPerson(list);
ViewBag.data = personlist;
和内部视图:
<td>@ViewBag.data.First().FirstName</td>
但这并没有显示值并给出错误提示Model.Person 不包含 First() 的定义"
But this does not show up the value and gives error saying "Model.Person doesnot contain a defibition for First()"
推荐答案
在您看来,您必须将其转换回原始类型.没有演员表,它只是一个对象.
In your view, you have to cast it back to the original type. Without the cast, it's just an object.
<td>@((ViewBag.data as ICollection<Person>).First().FirstName)</td>
ViewBag 是 C# 4 动态类型.除非强制转换,否则从它返回的实体也是动态的.但是,像 .First() 和所有其他 Linq 扩展方法 不使用动态.
ViewBag is a C# 4 dynamic type. Entities returned from it are also dynamic unless cast. However, extension methods like .First() and all the other Linq ones do not work with dynamics.
编辑 - 处理评论:
如果你想显示整个列表,就这么简单:
If you want to display the whole list, it's as simple as this:
<ul>
@foreach (var person in ViewBag.data)
{
<li>@person.FirstName</li>
}
</ul>
像 .First() 这样的扩展方法不起作用,但这个方法会起作用.
Extension methods like .First() won't work, but this will.
这篇关于如何使用 ViewBag 显示列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!