I'm working on an asp mvc application, and facing the following issue: I have a view that relates to a corresponding model. One of the model's properties is IEnumerable. I render it like the following:
<div id="DetailsTemplates">
@for (int i = 0; i < Model.Filter.itemDetails.Count; i++)
{
@Html.EditorFor(m => m.Filter.itemDetails[i], "ItemDetailsUserControl");
}
</div>
and ItemDetailsUserControl looks like that:
<div>
<table >
<tr>
<td>
@Html.TextBoxFor(model => model.ID, new {id = "id"})
</td>
<td >
@Html.TextBoxFor(model => model.Code, new {id = "code"})
</td>
<tr />
</table>
</div>
Now, I have 2 buttons in my view: Search button which is responsible for posting the whole form with all the input, and add button which adds another item to the Ienumerable collection of the model (and is supposed to add another template of the usercontrol).
My add button code is as follows:
$(".addButton").click(function (event) {
var a = $("#FilterForm").serialize();
event.preventDefault();
$.ajax({
url: '@Url.Action("AddBlankItemTemplate")',
data: $("#FilterForm").serialize()
}).success(function(partialView) {
$('#DetailsTemplates').append(partialView);
});
});
and the action in controller:
public ActionResult AddBlankItemTemplate(TaxCalculationFilterModel model)
{
var newItem = new DetailsDTO()
{
ID = "",
Code = 0
};
model.Filter.itemDetails.Add(newItem);
return PartialView("~/Views/Home/EditorTemplates/DetailsUserControl.cshtml", newItem);
}
The search button just posts the form with all the inputs/
Now, I can see that each click on the add button adds a template as I want. Then I fill in the data, and click on the search button. For both actions, AddBlankItemTemplate and the action of the search, the model's property of IEnumerable contains only count of 1. I can understand why, I guess there is no relation between the added templates and the model iteself. I tried to follow this article with no success: http://blogs.interknowlogy.com/2014/08/01/mvc-series-part-1-dynamically-adding-items-part-1/
Help :)