.net - 错误:asp.net MVC-5 模型项到 IEnumerable
问题描述
我正在使用 .NET MVC-5。我得到了上述错误。就我而言,我有一个名为“客户控制器”的控制器。其中包括两个名为“索引”和“详细信息”的操作结果。
索引正在从数据库中呈现客户列表。问题是如果我点击客户列表中的任何名称(由“索引”呈现)应该将我重定向到详细信息操作结果并显示与特定客户相关的详细信息。
客户控制器
public class CustomerController : Controller
{
private ApplicationDbContext _context;
public CustomerController()
{
_context = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
_context.Dispose();
}
// GET: Customer
public ActionResult Index()
{
var customers = _context.Customers.ToList();
return View(customers);
}
public ActionResult Details(int id)
{
var cus = _context.Customers.FirstOrDefault(c=> c.Id==id);
if (cus == null)
return HttpNotFound();
return View(cus);
}
}
索引 cshtml
<table class="table table-bordered table-responsive table-hover">
<thead>
<tr>
<th>Customer Name</th>
</tr>
</thead>
<tbody>
@foreach (var i in Model)
{
<tr>
<td>@Html.ActionLink(@i.Name, "Details", "Customer", new {id=1 }, null)</td>
</tr>
}
</tbody>
详细cshtml
<table class="table table-bordered table-hover table-responsive">
<thead>
<tr>
<th>Customer Id</th>
<th>Customer Name</th>
</tr>
</thead>
<tbody>
@foreach (var i in Model)
{
<tr>
<td> @i.Id @i.Name </td>
</tr>
}
</tbody>
解决方案
您正在使用 选择数据FirstOrDefault
,因此它将返回Customers
类的单个实体对象,并且您正在尝试对其进行迭代,这是错误的。
在这里,您可以使用2 种方式解决它。
1)在这里你会得到对象值,而foreach
不像下面这样。
<table class="table table-bordered table-hover table-responsive">
<thead>
<tr>
<th>Customer Id</th>
<th>Customer Name</th>
</tr>
</thead>
<tbody>
<tr>
<td> @i.Id @i.Name </td>
</tr>
</tbody>
2)如果您不想更改视图代码,那么您需要list
从控制器传递对象,如下所示。
public ActionResult Details(int id)
{
var cus = _context.Customers.FirstOrDefault(c=> c.Id==id);
List<Customers> lstcus = new List<Customers>();
lstcus.Add(cus);
if (cus == null)
return HttpNotFound();
return View(lstcus);
}
推荐阅读
- android - 带有自定义 PopupMenu 的窗口管理器
- matlab - 如何将 Y 定义为不同的 X 值(如直方图)
- java - GSON 在库模块中未序列化数据
- angular - 我怎么知道我已经在 Angular 应用程序中单点登录?
- python - 在 Python 中键入一个可变参数函数
- python - 我正在使用乌龟制作蛇游戏,但在制作程序功能时遇到问题,因为它没有移动
- python - 带有面部跟踪器的 python 运动面具
- r - 结合来自两个不同数据集的 glm 模型 (r/rpy2)
- flutter - 如何从给定的颜色中获得 Flutter 中的颜色阴影?
- node.js - 用笑话测试内部错误的存根函数