【问题标题】:pass linq query to view传递 linq 查询以查看
【发布时间】:2012-10-24 03:01:31
【问题描述】:

我做了一个 linq 查询,我想将它传递给视图,但它给了我这个错误

The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery`1[<>f__AnonymousType4`2[System.String,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1

我的视图模型

  public class ManageScoreViewModel
     {
         public string fullName { get; set; }
         public string teamName { get; set; }
     }

控制器

  public ActionResult Index()
        {
            MyteamViewModel ms = new MyteamViewModel ();
            var vm = (from u in db.Users
                     join tm in db.Team_Members
                     on u.user_id equals tm.user_id
                     join t in db.Teams
                     on tm.team_id equals t.team_id
                     orderby t.name
                     select new { fullName = u.firstName + u.lastName, teamName = t.name });
          //  var vmlist = vm.ToList();

            return View(vm);
        }

视图类型为 IEnumerable

@model IEnumerable<CTA2._0.ViewModels.ManageScoreViewModel>
@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.fullName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.teamName)
        </td>

我尝试将查询转换为列表 (var vmlist = vm.ToList();)。没用。任何帮助将不胜感激。

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    您的视图被强类型化为ManageScoreViewModel 集合,但您的 linq 查询使用投影返回一个匿名对象。您需要返回ManageScoreViewModel 对象的列表。您也可以在 linq 表达式上应用ToList() 方法

    改变

    select new { fullName = u.firstName + u.lastName, teamName = t.name });
    

    select new ManageScoreViewModel { fullName = u.firstName + u.lastName,
                                                      teamName = t.name }).ToList();
    

    【讨论】:

      猜你喜欢
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-23
      • 1970-01-01
      相关资源
      最近更新 更多