1

I have these two classes which I'm using as my view models:

public class CreateVm
{
    public int Id {get; set;}
    public string Name {get; set;}
    public ICollection<ItemVm> Items {get; set;}
}

public class ItemVm
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int Quantity {get; set;}
}

Then I have a view that looks something like this, some elements removed for simplicity:

@model CreateVm
@Html.EditorFor(m => m.Id)
@Html.EditorFor(m => m.Name)

<input type="button" id="myButton">

<table id="myTable">
<thead></thead>
<tbody></tbody>
<table>

and a javascript file:

("#myButton").click(function(){
   $.ajax({
      url: "/Item/AddItem/",
      data: 'html',
      success: function(data){
         $("#myTable").append(data);
      }         
   });
});

my controller is basically just returning a partial view that has the table row in it:

public ItemController : Controller
{
   public ActionResult AddItem()
   {
      var tableRow = new ItemVm();
      return PartialView("_AddItem", tableRow);
   }
}

partial view:

@model ItemVm

@EditorFor(m => m, null, "Items")

editor template:

@model ItemVm

<tr>
<td>@Html.EditorFor(m => m.Name)</td>
<td>@Html.EditorFor(m => m.Quantity)</td>
</tr>

Now the problem is that this is not generating the required inputs for mvc's binding to work, i.e., <input name="[0].Name">, how can I have the editor template (or some other element) produced those type of inputs so that it binds automatically to the CreateVm when posting the form?

SOfanatic
  • 5,523
  • 5
  • 36
  • 57
  • there's many people with the same problem every day. Here is another case, for that the answer is use something like [Angular](https://angularjs.org/) or [KnockoutJs](http://knockoutjs.com), and bind the hole object in `Controller` or `Api`. Here an example with knockout [Contacts Editor](http://knockoutjs.com/examples/contactsEditor.html) – mijail Oct 14 '15 at 15:22
  • anything that involves getting a list of some objects from the user, means a complex UI in one single page and javascript libraries solved the problem. – mijail Oct 14 '15 at 15:26
  • You can use the `BeginCollectionItem` html helper, or build the html in the client. Some examples [here](http://stackoverflow.com/questions/29161481/post-a-form-array-without-successful/29161796#29161796) and [here](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) –  Oct 14 '15 at 22:05

0 Answers0