【发布时间】:2017-10-25 07:45:53
【问题描述】:
public ActionResult Index()
{
return View(db.Employees.Select(x => new { x.First_Name, x.Last_Name,
x.Email }).ToList());
}
我的表 Employee 中有 5 列,它们是 First_Name、Last_Name、Address、Salary、Email。在这 5 列中,我只想在浏览器中显示 First_Name、Last_Name 和 Email。
这是我正在使用的视图
@model IEnumerable<crudOperation.Employee>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.DisplayNameFor(model => model.First_Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Last_Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Email)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.First_Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Last_Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
我收到的错误是:期间生成了未处理的异常 当前网络请求的执行。可以使用下面的异常堆栈跟踪来识别有关异常起源和位置的信息。
我是 asp.net Mvc 的初学者。我应该怎么做?
【问题讨论】:
-
您能否提供异常详细信息和错误堆栈跟踪?我认为
db.Employees.ToList()就足够了,您返回的是匿名类型而不是Employee表属性成员。 -
您的查询返回匿名对象的集合,而不是
Employee的集合只需删除您的.Select(...)并仅在视图中显示您想要的Employee的那些属性(但是为什么您有DisplayFor()用于属性Address和Salary如果您不想要它们?) -
您正在向视图发送匿名类型而不是
Employee。您需要从Employee创建一个具有所需属性的 DTO 类,然后将视图更改为@model IEnumerable<YourEmployeeDTO>像这样 stackoverflow.com/a/46905481/2946329 -
异常详细信息:System.InvalidOperationException:传入字典的模型项的类型为“System.Collections.Generic.List
1[<>f__AnonymousType43[System.String,System.String,System.String] ]',但此字典需要类型为“System.Collections.Generic.IEnumerable`1[crudOperation.Employee]”的模型项。 -
堆栈跟踪:[InvalidOperationException:传入字典的模型项的类型为“System.Collections.Generic.List
1[<>f__AnonymousType43[System.String,System.String,System.String]] ',但此字典需要类型为 'System.Collections.Generic.IEnumerable`1[crudOperation.Employee]' 的模型项。]
标签: c# asp.net-mvc entity-framework linq