首页 > 后端开发 > C++ > 如何正确发布从ASP.NET MVC到IEnumerable模型的表单阵列?

如何正确发布从ASP.NET MVC到IEnumerable模型的表单阵列?

Linda Hamilton
发布: 2025-02-02 04:01:09
原创
300 人浏览过

在ASP.NET MVC应用程序中,How to Properly POST Form Arrays from ASP.NET MVC to an IEnumerable Model?
> >

>>>需要将包含输入元素的动态数组的形式提交为iEnumerable< batchProductViewModel>模型属性。但是,当使用formCollection用作方法参数时,操作方法无法用form的数据绑定模型。

解决方案:
  • ,而不是使用formCollection,操作方法必须接受正确的模型类型的实例ConnectBatchProductViewModel,作为其参数。要生成一个形式,该表单将值形式为模型中的iEnumerable属性,请按照以下步骤:
>使用for for for loop来生成集合中每个元素的控件。每个控件都必须使用索引器命名才能正确绑定到模型。

>>在每个动态添加的行中添加一个隐藏的输入元素,以允许从视图删除项目。>将操作方法​​更新为将模型接收为参数。

>示例代码:

@for(int i = 0; i < Model.BatchProducts.Count; i++)
{
  <tr>
    <td>@Html.TextBoxFor(m => m.BatchProducts[i].Quantity)</td>
    <td>@Html.TextBoxFor(m => m.BatchProducts[i].BatchName)</td>
    <td>
      <input type="hidden" name="BatchProducts.Index" value="@i" />
      <a class="deleteRow"></a>
    </td>
  </tr>
}
登录后复制

表单代码:

public ActionResult Save(ConnectBatchProductViewModel model)
{
  // Model binding will populate the BatchProducts property with data from the form.
  ....
}
登录后复制

动作方法:

<div>
登录后复制

$("#addrow").click(function() {
  var index = (new Date()).getTime(); // unique indexer
  var clone = $('#NewBatchProduct').clone(); // clone the BatchProducts item
  // Update the index of the clone
  clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
  clone.html($(clone).html().replace(/"%"/g, '"' + index  + '"'));
  $("table.order-list").append(clone.html());
});
登录后复制
>动态添加和删除项目: 启用动态添加和删除项目,使用beginCollectionitem helper或一个HTML模板。动态添加新项目的模板是:> 添加一个新批处理产品的脚本将是:

以上是如何正确发布从ASP.NET MVC到IEnumerable模型的表单阵列?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板