首頁 >後端開發 >C++ >如何使用ASP.NET MVC和jQuery成功發布表單數組?

如何使用ASP.NET MVC和jQuery成功發布表單數組?

Mary-Kate Olsen
Mary-Kate Olsen原創
2025-02-02 04:16:10899瀏覽

How to Successfully POST a Form Array with ASP.NET MVC and jQuery?

>故障排除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。 ConnectBatchProductViewModelBatchProducts>動態數組管理(add/remove)

> >用於使用jQuery的動態添加和刪除項目,請考慮使用

助手或製定自定義的HTML模板有效地管理數組元素。 (有關這些技術的更多詳細信息,請參見[相關的在線資源/鏈接 -

>如果可用的BatchProductViewModel>]。

以上是如何使用ASP.NET MVC和jQuery成功發布表單數組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn