我想在视图上显示SQL数据。但我不能在控制器上:
var comments = (from p in ctx.Profiles
join sc in ctx.SuggestionComments on p.UserId equals sc.Crtr
join s in ctx.Suggestions on sc.SuggestionId equals s.Id
join u in ctx.Users on s.Crtr equals u.Id
where u.Email == mail
orderby sc.Crtm descending
select new { p.UserName, p.UserId, p.PhotoUrl, OneriId = s.Id, sc.Crtm }
).Take(10);
ViewBag.commentss = comments;
在视图上:
@foreach (var items in ViewBag.commentss)
{
<tr>
<td>
@items.UserName
</td>
<td>
@items.UserId
</td>
<td>
@items.PhotoUrl
</td>
<td>
@items.OneriId
</td>
<td>
@items.Crtm
</td>
</tr>
}
它不起作用:
Additional information: 'object' a 'UserName' not contains...
答案 0 :(得分:0)
ViewBag.commentss
将返回Object
,因此您无法对此进行foreach
循环。
因此,不要使用匿名类型,而是创建一个具有相关属性的类。 所以在你的案例中,类就是这样的。
Public class UserDetails
{
public string UserName{get;set;}
public int UserId{get;set;}
public string PhotoUrl{get;set;}
public int OneriId {get;set;}
public string Crtm{get;set;}
}
现在修改您的linq
查询,如下所示
var comments = (from p in ctx.Profiles
join sc in ctx.SuggestionComments on p.UserId equals sc.Crtr
join s in ctx.Suggestions on sc.SuggestionId equals s.Id
join u in ctx.Users on s.Crtr equals u.Id
where u.Email == mail
orderby sc.Crtm descending
select new UserDetails{UserName = p.UserName, UserId =p.UserId,PhotoUrl= p.PhotoUrl, OneriId = s.Id, Crtm =sc.Crtm }).Take(10);
ViewBag.commentss = comments;
现在在视野中。你可以按照以下
对你的viewbag进行类型转换var userDetails = ViewBag.commentss as List<UserDetails>;
然后你可以运行foreach循环
foreach(var userDetail in userDetails )
{
// Write your code here
}