我有一个局部视图,其中包含文本字段并绑定到设置的列表,因此本质上存在一行文本字段,用户可以向其中添加另一行或从中删除一行。我通过像这样遍历列表来构建视图:
@model PricingRequestWebApp.Web.Models.PricingRequestModel
<div id="shiplocation-wrapper">
<table class="shipinfoprtable">
<thead>
<tr>
<th>@Html.LabelFor(m => m.ShippingLocationsModel[0].Address)<span class="formRed">*</span></th>
<th>@Html.LabelFor(m => m.ShippingLocationsModel[0].City)<span class="formRed">*</span></th>
<th>@Html.LabelFor(m => m.ShippingLocationsModel[0].State)<span class="formRed">*</span></th>
<th>@Html.LabelFor(m => m.ShippingLocationsModel[0].Zip)<span class="formRed">*</span></th>
<th>@Html.LabelFor(m => m.ShippingLocationsModel[0].PFreight)<span class="formRed">*</span></th>
<th>@Html.LabelFor(m => m.ShippingLocationsModel[0].FreightType)<span class="formRed">*</span></th>
<td><span class="link" id="addlocation" onclick="AddShippingLocation()">Add</span></td>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.ShippingLocationsModel.Count; i++)
{
<tr>
<td>@Html.TextBoxFor(m => m.ShippingLocationsModel[i].Address, new { @style = "width: 200px" })</td>
<td>@Html.TextBoxFor(m => m.ShippingLocationsModel[i].City, new { @style = "width: 150px" })</td>
<td>@Html.TextBoxFor(m => m.ShippingLocationsModel[i].State, new { @size = 3 })</td>
<td>@Html.TextBoxFor(m => m.ShippingLocationsModel[i].Zip, new { @style = "width: 80px" })</td>
<td>@Html.TextBoxFor(m => m.ShippingLocationsModel[i].PFreight, new { @style = "width: 80px" })</td>
<td>@Html.TextBoxFor(m => m.ShippingLocationsModel[i].FreightType, new { @style = "width: 200px" })</td>
@if (Model.ShippingLocationsModel.Count > 1)
{
<td><span class="link" id="removelocation" onclick="RemoveShippingLocation(@i);">Remove</span></td>
}
</tr>
}
</tbody>
</table>
</div>
我的控制器方法如下所示:
[HttpPost]
public ActionResult AddShippingLocation(PricingRequestModel model)
{
model.ShippingLocationsModel.Add(new ShippingLocationsModel());
return PartialView("shiplocationsPartial", model);
}
[HttpPost]
public ActionResult RemoveShippingLocation(PricingRequestModel model)
{
model.ShippingLocationsModel.RemoveAt(StaticItems.id);
return PartialView("shiplocationsPartial", model);
}
还有我发布数据并返回视图的 Jquery 函数:
function AddShippingLocation() {
$.ajax({
data: $('#shippinginfoform').serialize(),
type: "POST",
url: "/PricingRequest/AddShippingLocation",
success: function (response) {
$('#shiplocation-wrapper').html(response);
}
})
}
function RemoveShippingLocation(id) {
$.ajax({
data: { id: id },
type: "POST",
url: "/PricingRequest/SaveID",
complete: function () {
$.ajax({
data: $('#shippinginfoform').serialize(),
cache: false,
type: "POST",
url: "/PricingRequest/RemoveShippingLocation",
success: function (response) {
$('#shiplocation-wrapper').html(response);
}
})
}
})
}
现在,假设我在用户视图中创建了 4 个项目。我单击第 2 项将其删除,并将 i 作为 id 传入。然后,我将其从模型列表中删除,并使用更新的模型传回视图。我现在已经调试了至少 50 次,并且控制器方法看起来与它应该的完全一样,并且视图中的数据也是如此。令人费解的是,尽管 ajax 上的响应与我在调试时看到的不同。单击删除项目 2 会删除项目 4。如果我有 5 个项目,则无论我单击要删除什么项目,都会删除项目 5。它始终是被删除的最后一项。我知道我必须在这里遗漏一些东西,但我看不到什么。有任何想法吗?谢谢。