无法在 MVC5 Asp.Net 视图上显示 SQL 数据



我想在视图上显示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...

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;

现在在视野中。您可以按如下方式键入您的视袋

var userDetails = ViewBag.commentss as List<UserDetails>;

然后你可以运行foreach循环

foreach(var userDetail in userDetails )
{
  // Write your code here
}

最新更新