成功地在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中文网其他相关文章!