我正在使用.NET MVC-5。我得到了上面的错误。在我的例子中,我有一个名为“客户控制器”的控制器。它由两个操作结果组成,命名为“索引”和“Details”。
索引显示数据库中的客户列表。问题是,如果我单击客户列表中的任何一个名称(由“索引”呈现),应该将我重定向到详细操作结果,并显示与特定客户相关的详细信息。
客户控制器
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>
发布于 2019-11-19 07:33:19
您正在使用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);
}https://stackoverflow.com/questions/58928395
复制相似问题