我在Controller中有以下操作:
public ViewResult Index()
{
//select
var query = (from u in db.UserSets
join f in db.FriendRequestsSets on u.ID equals f.FriendID
orderby u.ID
select new {Id = u.ID, Nickname = u.Nickname}).AsEnumerable();
ViewBag.FriendRequests = query;
return View(this.UserColl());
}
Razor视图中的以下foreach:
<ul>
@foreach (var item in ViewBag.FriendRequests)
{
<li>@item.Nickname</li>
}
</ul>
以下错误:
*'object' does not contain a definition for 'Nickname'*
我的代码中缺少什么?
答案 0 :(得分:6)
ViewBag是object类型,而不是Enumerable!
你可以做的是,有一个课程如下:
Class User{
public int Id;
public string Nickname;
}
然后填写User类列表:
var query = (from u in db.UserSets
join f in db.FriendRequestsSets on u.ID equals f.FriendID
orderby u.ID
select new User{Id = u.ID, Nickname = u.Nickname}).ToList();
最后在你看来这样做:
@foreach (var item in ViewBag.FriendRequests as List<User> )
{
<li>@item.Nickname</li>
}
希望它有所帮助。