ASP.Net 如何访问列表中的正确项目
ASP.Net How can I access the correct item in the list
我在ASP.Net的世界里还是个初学者。
我的问题是我认为很容易回答。
我有一个在视图中使用 foreach 显示的产品列表:
@using (Html.BeginForm("Edit", "Products")){
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Id</th>
<th scope="col">Info</th>
<th scope="col">Count</th>
</tr>
</thead>
<tbody>
@foreach (var product in Model.ProductsList)
{
<tr>
<th scope="row">@Html.HiddenFor(x => product.Id)</th>
<td>@Html.TextBoxFor(x => product.Info) </td>
<td>@Html.TextBoxFor(x => product.Count) </td>
</tr>
}
</tbody>
</table>
<button type="submit" class="btn btn-primary">Save</button>}
如果我现在尝试使用此方法找到正确的元素,例如:列表中有 10 个元素,我单击第 5 个元素并更改信息。
如果我现在单击“保存”,我应该取回我在我的方法中编辑的 5 个元素。
[HttpPost]
public ActionResult Edit(Product product)
{
if (product == null)
return HttpNotFound();
using (var _context = new Models.Database_.WebContext())
{
var result = _context.Products.SingleOrDefault(x => x.Id == product.Id);
}
return RedirectToAction("Index");
}
我想我缺少的是我必须提供身份证件?!
错误是我的ID总是0.
您不必传递 Id,因为您传递的是视图中的整个模型。您的模型未绑定到您的 ActionResult 参数产品。因此,您得到空对象。
将您的代码更改为:
<th scope="row">@Html.Hidden("Id", product.Id)</th>
<td>@Html.TextBox("Info", product.Info) </td>
<td>@Html.TextBox("Count", product.Count) </td>
我记得,"name" 属性用于映射。因此,在进行上述更改后,如果您检查(浏览器上的 F12)您的 HTML 您将看到 "name" 属性将附加到您的 HTML 元素。
我还注意到一个问题,您的 ActionResult 接受 Product 对象,但在您看来您提交的是产品列表。不确定你为什么这样做。
我在ASP.Net的世界里还是个初学者。 我的问题是我认为很容易回答。
我有一个在视图中使用 foreach 显示的产品列表:
@using (Html.BeginForm("Edit", "Products")){
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Id</th>
<th scope="col">Info</th>
<th scope="col">Count</th>
</tr>
</thead>
<tbody>
@foreach (var product in Model.ProductsList)
{
<tr>
<th scope="row">@Html.HiddenFor(x => product.Id)</th>
<td>@Html.TextBoxFor(x => product.Info) </td>
<td>@Html.TextBoxFor(x => product.Count) </td>
</tr>
}
</tbody>
</table>
<button type="submit" class="btn btn-primary">Save</button>}
如果我现在尝试使用此方法找到正确的元素,例如:列表中有 10 个元素,我单击第 5 个元素并更改信息。 如果我现在单击“保存”,我应该取回我在我的方法中编辑的 5 个元素。
[HttpPost]
public ActionResult Edit(Product product)
{
if (product == null)
return HttpNotFound();
using (var _context = new Models.Database_.WebContext())
{
var result = _context.Products.SingleOrDefault(x => x.Id == product.Id);
}
return RedirectToAction("Index");
}
我想我缺少的是我必须提供身份证件?! 错误是我的ID总是0.
您不必传递 Id,因为您传递的是视图中的整个模型。您的模型未绑定到您的 ActionResult 参数产品。因此,您得到空对象。
将您的代码更改为:
<th scope="row">@Html.Hidden("Id", product.Id)</th>
<td>@Html.TextBox("Info", product.Info) </td>
<td>@Html.TextBox("Count", product.Count) </td>
我记得,"name" 属性用于映射。因此,在进行上述更改后,如果您检查(浏览器上的 F12)您的 HTML 您将看到 "name" 属性将附加到您的 HTML 元素。
我还注意到一个问题,您的 ActionResult 接受 Product 对象,但在您看来您提交的是产品列表。不确定你为什么这样做。