>故障排除ASP.NET MVC表单阵列提交使用JQUERY
>本文解决了一个常见问题:使用ASP.NET MVC和jQuery提交表单数组,在尝试访问控制器中的数组数据时,导致null引用异常。 当表单的数组元素未正确索引以绑定正确的模型时,通常会出现问题。
。 该解决方案需要在循环中生成形式控件,以确保使用索引器正确命名每个元素。 此外,服务器端模型属性(IEnumerable<BatchProductViewModel>
)应为BatchProducts
,以适应动态数组尺寸。IList<BatchProductViewModel>
>
<code class="language-csharp">@using (Html.BeginForm("Save", "ConnectBatchProduct", FormMethod.Post)) { // ... other form elements ... // Correctly indexed form elements for the array // This loop ensures each element in the array has a unique index // The indexer is crucial for proper model binding for (int i = 0; i < Model.BatchProducts.Count; i++) { @Html.HiddenFor(model => model.BatchProducts[i].ProductId) // Example property @Html.TextBoxFor(model => model.BatchProducts[i].ProductName) // Example property // ... other properties for BatchProductViewModel ... } // ... rest of the form ... <input type="submit" value="Save" /> }</code>>通过这些调整,控制器中的
>操作方法将正确接收一个填充的Save
对象,包括其ConnectBatchProduct
> list。
ConnectBatchProductViewModel
BatchProducts
>动态数组管理(add/remove)
> >用于使用jQuery的动态添加和删除项目,请考虑使用
助手或制定自定义的HTML模板有效地管理数组元素。 (有关这些技术的更多详细信息,请参见[相关的在线资源/链接 ->如果可用的BatchProductViewModel
>]。
以上是如何使用ASP.NET MVC和jQuery成功发布表单数组?的详细内容。更多信息请关注PHP中文网其他相关文章!