Pulling my hear out with this.
I have a model that has a list of items as part of it. This is "Costs"
In it's Edit view I use a for loop to show the items via an Editor Template.
I have added a link to append a new one to it, ensuring the Ids and Names generated follow the the others.. ie ID = Costs_N__PropertyName Name = Costs[N].PropertyName
The link calls an action which returns that sam EditorTemplate but with custome names & Ids as per above. A new blank row appears as expected and I am able to edit it. However, when I attempt to save I can see that it isn't bound to the model.
I can't belive this is giving me such grief, I'd imagine that this is common place.
I'm guessing that I am missingh something obvious but I cannot see it..
In short, it all appears to be working but the appended item does not get bound the the main models Costs list. Please please please help....Code below.
EDit view portion
<div class="form-group">
<div class="col-md-6 col-lg-offset-1">
<table id="tblCosts" class="table">
<thead>
<tr>
<th>@Html.DisplayNameFor(model => model.Costs[0].ValidFrom)</th>
<th>@Html.DisplayNameFor(model => model.Costs[0].ValidTo)</th>
<th>@Html.DisplayNameFor(model => model.Costs[0].InternalCost)</th>
</tr>
</thead>
<tbody id="editorRows">
@{
for (int i = 0; i < Model.Costs.Count; i++)
{
@Html.EditorFor(m => Model.Costs[i]);
}
}
</tbody>
</table>
</div>
</div>
JQuery Calling action to add new row...
$("#addItem").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) {
alert(html);
$("#editorRows").append(html);
}
});
Action to add new
public PartialViewResult BlankCostRow( int tmpId )
{
var itemModel = new ECodeLevel2CostViewModel();
itemModel.Id = tmpId;
return this.PartialView("~/Views/Shared/EditorTemplates/ECodeLevel2CostViewModel.cshtml", itemModel);
}
And the EditorTemplate...
@if (Model.Id >= 0)
{
<tr>
<td>
@Html.HiddenFor(model => model.UniqueId)
@Html.HiddenFor(model => model.Id)
@Html.EditorFor(model => model.ValidFrom)
</td>
<td>
@Html.EditorFor(model => model.ValidTo)
</td>
<td>
@Html.EditorFor(model => model.InternalCost)
</td>
</tr>
}
else
{
Layout = "";
string prefix = "Costs";
string idPreifx = String.Format("{0}_{1}__", prefix, -Model.Id);
string namePreifx = String.Format("{0}[{1}].", prefix, -Model.Id);
<tr>
<td>
@Html.Hidden(@namePreifx + "UniqueId", Model.UniqueId, new { name = @namePreifx + "UniqueId" })
@Html.Hidden(@namePreifx + "Id", Model.Id, new { name = @namePreifx + "Id" })
@Html.TextBox(@namePreifx + "ValidFrom", Model.ValidFrom, new { name = @namePreifx + "ValidFrom" })
</td>
<td>
@Html.TextBox(@namePreifx + "ValidTo", Model.ValidTo, new { name = @namePreifx + "ValidTo" })
</td>
<td>
@Html.TextBox(@namePreifx + "InternalCost", Model.InternalCost, new { name = @namePreifx + "InternalCost" })
</td>
</tr>
}