c# - POST 表单数组没有成功

标签 c# html asp.net-mvc forms

我正在使用 C# 和 .NET Framework 4.5.1 开发 ASP.NET MVC 5 网站。

我有这个formcshtml文件:

@model MyProduct.Web.API.Models.ConnectBatchProductViewModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>
    @if (@Model != null)
    { 
        <h4>Producto: @Model.Product.ProductCode, Cantidad: @Model.ExternalCodesForThisProduct</h4>
        using (Html.BeginForm("Save", "ConnectBatchProduct", FormMethod.Post))
        {
            @Html.HiddenFor(model => model.Product.Id, new { @id = "productId", @Name = "productId" });

            <div>
                <table id ="batchTable" class="order-list">
                    <thead>
                        <tr>
                            <td>Cantidad</td>
                            <td>Lote</td>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>@Html.TextBox("ConnectBatchProductViewModel.BatchProducts[0].Quantity")</td>
                            <td>@Html.TextBox("ConnectBatchProductViewModel.BatchProducts[0].BatchName")</td>
                            <td><a class="deleteRow"></a></td>
                        </tr>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="5" style="text-align: left;">
                                <input type="button" id="addrow" value="Add Row" />
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>
            <p><input type="submit" value="Seleccionar" /></p>
        }
    }
    else
    { 
        <div>Error.</div>
    }
<script src="~/Scripts/jquery-2.1.3.min.js"></script>
<script src="~/js/createBatches.js"></script> <!-- Resource jQuery -->    
</body>
</html>

这是 Action 方法:

[HttpPost]
public ActionResult Save(FormCollection form)
{
    return null;
}

还有两个ViewModel :

public class BatchProductViewModel
{
    public int Quantity { get; set; }
    public string BatchName { get; set; }
}

public class ConnectBatchProductViewModel
{
    public Models.Products Product { get; set; }
    public int ExternalCodesForThisProduct { get; set; }

    public IEnumerable<BatchProductViewModel> BatchProducts { get; set; }
}

但我在 FormCollection form 中得到了这个变量: enter image description here

但我想得到一个 IEnumerable<BatchProductViewModel> model :

public ActionResult Save(int productId, IEnumerable<BatchProductViewModel> model);

如果我使用上面的方法签名,两个参数都是空的。

我想要一个 IEnumerable因为用户将使用 jQuery 动态添加更多行。

这是 jQuery脚本:

jQuery(document).ready(function ($) {
    var counter = 0;

    $("#addrow").on("click", function () {

        counter = $('#batchTable tr').length - 2;

        var newRow = $("<tr>");
        var cols = "";

        var quantity = 'ConnectBatchProductViewModel.BatchProducts[0].Quantity'.replace(/\[.{1}\]/, '[' + counter + ']');
        var batchName = 'ConnectBatchProductViewModel.BatchProducts[0].BatchName'.replace(/\[.{1}\]/, '[' + counter + ']');

        cols += '<td><input type="text" name="' + quantity + '"/></td>';
        cols += '<td><input type="text" name="' + batchName + '"/></td>';

        cols += '<td><input type="button" class="ibtnDel"  value="Delete"></td>';
        newRow.append(cols);

        $("table.order-list").append(newRow);
        counter++;
    });


    $("table.order-list").on("click", ".ibtnDel", function (event) {
        $(this).closest("tr").remove();

        counter -= 1
        $('#addrow').attr('disabled', false).prop('value', "Add Row");
    });
});

有什么想法吗?

我检查过这个SO answer , 和 this article但我的代码无法正常工作。

最佳答案

您需要在 for 中为集合生成控件循环以便使用索引器正确命名它们(注意属性 BatchProducts 需要是 IList<BatchProductViewModel>

@using (Html.BeginForm("Save", "ConnectBatchProduct", FormMethod.Post))
{
  ....
  <table>
    ....
    @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>
          // add the following to allow for dynamically deleting items in the view
          <input type="hidden" name="BatchProducts.Index" value="@i" />
          <a class="deleteRow"></a>
        </td>
      </tr>
    }
    ....
  </table>
  ....
}

那么POST方法需要是

public ActionResult Save(ConnectBatchProductViewModel model)
{
  ....
}

编辑

注意:在您的编辑之后,如果您想动态添加和删除 BatchProductViewModel在他看来,你需要使用 BeginCollectionItem this answer 中讨论的助手或 html 模板

动态添加新项目的模板是

<div id="NewBatchProduct" style="display:none">
  <tr>
    <td><input type="text" name="BatchProducts[#].Quantity" value /></td>
    <td><input type="text" name="BatchProducts[#].BatchName" value /></td>
    <td>
      <input type="hidden" name="BatchProducts.Index" value ="%"/>
      <a class="deleteRow"></a>
    </td>
  </tr>
</div>

注意虚拟索引器和隐藏输入的不匹配值会阻止此模板回发。

然后脚本添加一个新的BatchProducts会是

$("#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());
});

关于c# - POST 表单数组没有成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29161481/

相关文章:

异步 Web 响应的 C# 批处理在完成之前挂起

c# - Excel 2007 中的数值 - 底层 xml 文件中的表示与存储

javascript - 样式表和脚本包在 Mono 中不起作用

c# - 无法加载 PDF 文档 (MVC)

C# - IDataReader 到使用泛型的对象映射

c# - 使用c#获取onload隐藏字段值

javascript - 变量未在函数链末尾更新

javascript - jQuery 用户界面 : draggable on dragenter

html - ViewRight-player 顶部的 Div

asp.net-mvc - Blazor HttpClient 3.2.0 Get 调用抛出异常,因为响应 header 内容类型与 GetFromJsonAsync 不兼容