首页 > 解决方案 > 如何将控制器中的列表读取到 Mvc 中的 foreach 视图中?

问题描述

我收到了这个错误

传入字典的模型项的类型为“System.Collections.Generic.List'1[CandidateScreening.Data.Entities.Patient]”,但此字典需要类型为“System.Collections.Generic.IEnumerable”1 的模型项[CandidateScreening.Models.Patient]'。)

public ActionResult Index()
{
    var Patient = _context.Patients.ToList();
    return View(Patient);
}


@model IEnumerable<CandidateScreening.Models.Patient>
@{
    ViewBag.Title = "index";
}
<h2>List Of the Patient</h2>
<table class="table">
    <thead>
        <tr>
            <th>firstName</th>
            <th>SurName</th>
            <th>Gender</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td> @Html.ActionLink(item.Firstname, "Index", "detail")</td>
                <td> @Html.ActionLink(item.Surname, "Index", "detail")</td>
                <td> @Html.ActionLink(item.Gender, "Index", "detail")</td>


            </tr>
        }
    </tbody>
</table>

你能告诉我为什么会出现这个错误吗?我已经尝试更改IEnumerableList但还没有工作

标签: asp.net-mvc

解决方案


假设Patients是一个实体框架数据上下文,ToList()将生成对象类型设置为的列表IEnumerable<CandidateScreening.Data.Entities.Patient>,该列表与指令设置的对象类型不匹配@model(即IEnumerable<CandidateScreening.Models.Patient>)。

要解决这个问题,只需使用Select()LINQ 查询将实体上下文投影到视图模型类列表中:

public ActionResult Index()
{
    var Patient = _context.Patients.Select(x => new CandidateScreening.Models.Patient
    {
        // list of properties here
        // example:
        // PatientId = x.PatientId
    }).ToList();    

    return View(Patient);
}

或使用查询表达式作为替代:

var Patient = (from patient in _context.Patients
              select new CandidateScreening.Models.Patient
              {
                  // list of properties here
                  // example:
                  // PatientId = patient.PatientId
              }).ToList();

推荐阅读