asp.net-mvc - 如何将控制器中的列表读取到 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>
你能告诉我为什么会出现这个错误吗?我已经尝试更改IEnumerable
为List
但还没有工作
解决方案
假设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();
推荐阅读
- ruby-on-rails - Rails 6 在 url 中使用两个参数为端点创建新路由
- python - 如果导致系列的真值不明确的条件。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
- algorithm - 我们如何实现优先队列而不是队列到广度优先遍历?
- r - R表仅在更改如何在没有for循环的情况下拥有所有值时才具有值
- php - 判断 Yii 1 应用是否从同域的外部应用登录
- vue.js - 在路由器链接中包装卡片以更改为另一个视图
- javascript - Array.push 不适用于方法的返回
- go - 为什么变量没有在 for 循环内更新?
- python - 如何从列表中找到最短的公共子字符串?
- python - 遍历一列中的唯一字符串,并从与唯一字符串关联的其他 2 列创建字典或数据数组