【发布时间】:2019-02-25 06:14:14
【问题描述】:
我在尝试使用列表脚手架从数据库中获取数据时遇到错误。错误和代码如下。
我的模特:
namespace ShimbaSchool.Models
{
[Table("tblStaff")]
public class Staff
{
[Key]
public int StaffId { get; set; }
[Required]
[DisplayName("Upload Image")]
public string ImagePath { get; set; }
[Required,MinLength(2),DisplayName("Staff Name")]
public string StaffName { get; set; }
[Required,MaxLength(250)]
[DisplayName("Teacher's Subject")]
public string StaffSpecialty { get; set; }
[NotMapped]
public HttpPostedFileBase ImageFile { get; set; }
}
}
我的控制者:
namespace ShimbaSchool.Controllers
{
public class StaffController : Controller
{
EventMessageDepartmentContext db = new EventMessageDepartmentContext();
public ActionResult Index()
{
return View(db.StaffTable.ToList());
}
}
}
观点:
@model IEnumerable<ShimbaSchool.Models.Staff>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_MyLayout.cshtml";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.ImagePath)
</th>
<th>
@Html.DisplayNameFor(model => model.StaffName)
</th>
<th>
@Html.DisplayNameFor(model => model.StaffSpecialty)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ImagePath)
</td>
<td>
@Html.DisplayFor(modelItem => item.StaffName)
</td>
<td>
@Html.DisplayFor(modelItem => item.StaffSpecialty)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.StaffId }) |
@Html.ActionLink("Details", "Details", new { id=item.StaffId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.StaffId })
</td>
</tr>
}
</table>
执行时出现错误:
传入字典的模型项的类型为“System.Collections.Generic.List 1[ShimbaSchool.Models.Staff]”,但此字典需要类型为“System.Collections.Generic.IEnumerable 1[”的模型项ShimbaSchool.Models.EventMessageDepartment]'。
请帮我解决这个问题,理解逻辑,这样就没有下次了。要添加,我将相同的模型与另一个控制器一起使用,尽管视图在同一项目的不同布局上呈现,但它工作正常。
【问题讨论】:
-
实际上,您从控制器方法传递到视图的列表是
List of EventMessageDepartment,而不是List of Staff。请检查它并将List of Staff从控制器方法传递到视图。 -
其实你在控制器上看到的EventMessageDepartmentContext就是我的数据上下文,可以和db进行通信。
-
是的!但您必须正确选择表格。更好地使用团队查看器 ID 和通行证进行远程访问。我会解决你的问题。
-
1 421 119 183 你不能从我发布的代码中纠正>
标签: c# sql-server asp.net-mvc entity-framework