>故障排除ASP.NET MVC表單陣列提交使用JQUERY
>本文解決了一個常見問題:使用ASP.NET MVC和jQuery提交表單數組,在嘗試訪問控制器中的數組數據時,導致null引用異常。 當表單的數組元素未正確索引以綁定正確的模型時,通常會出現問題。
。 該解決方案需要在循環中生成形式控件,以確保使用索引器正確命名每個元素。 此外,服務器端模型屬性(IEnumerable<BatchProductViewModel>
)應為BatchProducts
,以適應動態數組尺寸。 IList<BatchProductViewModel>
>
@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" /> }
>操作方法將正確接收一個填充的Save
對象,包括其ConnectBatchProduct
> list。
ConnectBatchProductViewModel
BatchProducts
>動態數組管理(add/remove)
> >用於使用jQuery的動態添加和刪除項目,請考慮使用
助手或製定自定義的HTML模板有效地管理數組元素。 (有關這些技術的更多詳細信息,請參見[相關的在線資源/鏈接 ->如果可用的BatchProductViewModel
>]。
以上是如何使用ASP.NET MVC和jQuery成功發布表單數組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!