POST a form array without successful

后端 未结 5 1270
误落风尘
误落风尘 2020-11-21 05:07

I\'m developing an ASP.NET MVC 5 web with C# and .NET Framework 4.5.1.

I have this form in a cshtml file:

@model MyProduct.         


        
5条回答
  •  广开言路
    2020-11-21 05:41

    You need to generate the controls for the collection in a for loop so they are correctly named with indexers (note that property BatchProducts needs to be IList

    @using (Html.BeginForm("Save", "ConnectBatchProduct", FormMethod.Post))
    {
      ....
      
        ....
        @for(int i = 0; i < Model.BatchProducts.Count; i++)
        {
          
        }
        ....
      
    @Html.TextBoxFor(m => m.BatchProducts[i].Quantity) @Html.TextBoxFor(m => m.BatchProducts[i].BatchName) // add the following to allow for dynamically deleting items in the view
    .... }

    Then the POST method needs to be

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

    Edit

    Note: Further to your edit, if you want to dynamically add and remove BatchProductViewModel items in he view, you will need to use the BeginCollectionItem helper or a html template as discussed in this answer

    The template to dynamically add new items would be

    
    

    Note the dummy indexers and the non-matching value for the hidden input prevents this template posting back.

    Then the script to add a new BatchProducts would be

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

提交回复
热议问题