【发布时间】:2018-04-30 12:46:25
【问题描述】:
我正在尝试将对象列表从控制器传递到 View ,其中使用 LINQ 从数据库中检索对象的属性。型号代码如下:
public class Department
{
[Key]
public int DepartmentId { get; set; }
[Required(ErrorMessage = "Enter Department Name")]
[DisplayName("Department Name")]
public string DepartmentName { get; set; }
}
控制器代码是:
public ActionResult ShowDepartments()
{
var departmentList = db.Deapartment.Select(x => new
{
x.DepartmentId,
x.DepartmentName
}).ToList();
return View(departmentList);
}
查看代码是:
@model List<PractiseMVC11_17_2017.Models.Department>
@{
ViewBag.Title = "ShowDepartments";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Show Departments</h2>
<div>
<table class="table table-bordered table-hover">
<tbody>
@foreach (var department in Model)
{
<tr>
<td>
@department.DepartmentId
</td>
<td>
@department.DepartmentName
</td>
</tr>
}
</tbody>
</table>
</div>
}
但是当我运行项目时,它显示以下异常:
异常详细信息:System.InvalidOperationException:传入字典的模型项的类型为“System.Collections.Generic.List1[<>f__AnonymousType32[System.Int32,System.String]]”,但此字典需要模型'System.Collections.Generic.List`1[PractiseMVC11_17_2017.Models.Department]'类型的项目。
【问题讨论】:
标签: linq asp.net-mvc-5