成功地在ASP.NET MVC
中發布表單數組>本文解決了使用C#和.NET Framework 4.5.1或更高版本提交包含ASP.NET MVC應用程序數組的表單數據時遇到的挑戰。 重點是在控制器的操作方法中正確發布和檢索表單數組數據。
了解ASP.NET MVC 中的數組綁定 在ASP.NET MVC中,
通常將數組作為集合處理,通常為>或IEnumerable
>。 正確綁定數據與這些集合需要特定的語法和模型聲明。
IList
>修訂的代碼
這是一種改進的方法,以確保成功的形式數組提交和檢索:
表格標記(示例):
控制器操作方法:
<code class="language-html">@using (Html.BeginForm("Save", "ConnectBatchProduct", FormMethod.Post)) { <!-- ... your form elements here ... --> }</code>
模型聲明:
確保您的<code class="language-csharp">[HttpPost] public ActionResult Save(ConnectBatchProductViewModel model) { // Process the model.BatchProducts collection here // ... }</code>
(或)以正確接收數組數據。
修改的jQuery腳本(示例):ConnectBatchProductViewModel
>
IList<BatchProductViewModel>
IEnumerable<BatchProductViewModel>
此jQuery代碼動態生成每個數組元素的唯一索引器,從而確保適當的綁定。 它遍及所有元素,都使用a
關鍵因素:
<code class="language-javascript">$("#addrow").click(function() { var index = (new Date()).getTime(); var clone = $('#NewBatchProduct').clone(); clone.find('[name]').each(function() { $(this).attr('name', $(this).attr('name').replace(/\[#\]/g, '[' + index + ']')); }); $("table.order-list").append(clone); });</code>
name
>name
模型屬性類型:
>或,其中是您的單個數組元素的視圖模型。
>IList<T>
IEnumerable<T>
>T
錯誤處理:BatchProducts[0].ProductName
>以上是如何在ASP.NET MVC中成功發布表單數組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!