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?