I am using a view model and a partial view to insert a row using AJAX. When a new row is inserted the ViewModel's ID (AttributeDefinitionID
) is set to zero. On save, the ID is updated and sent back out the view. However the helper that binds to ID seems to still have the old value.
View model
public class AttributeEntryViewModel
{
public int AttributeDefinitionID { get; set; }
[Required]
[MaxLength(255, ErrorMessage = "Name must be less than
255 characters in length.")]
public string Name { get; set; }
}
Partial view "_AttributeEntryPartial.cshtml"
@model ICMDB.ViewModels.AttributeEntryViewModel
<tr id ="@Model.AttributeDefinitionID" >
@Html.HiddenFor(model => model.AttributeDefinitionID)
<td>
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</td>
<td>
<a href="#" onclick="RemoveAttribute(@Model.AttributeDefinitionID);
return false;">Remove</a>
</td>
</tr>
For some reason, the Html Helper Html.HiddenFor
doesn't bind to the correct value and produces the following Html:
<tr id="40850">
<input id="AttributeDefinitionID" type="hidden" value="0"
name="AttributeDefinitionID" data-val-required="The
AttributeDefinitionID field is required." data-val-number= "The
field AttributeDefinitionID must be a number." data-val="true">
You can see that it has inserted the ID correctly in the row tag (<tr id = "40850">
) but not in the input tag (value="0"
). That should read value="40850"
.
Any ideas? Is the Html Helper or the browser caching the value?
EDIT: The AJAX function AddAttribute simply calls a controller function of the same name and appends the resulting partial (the partial listed above) to a table:
function AddAttribute() {
// and send it as AJAX request
$.ajax({
url: '@Url.Action("AddAttribute")',
type: 'POST',
cache: false,
success: function (result) {
// when the AJAX succeeds add result to the table
$('#AttributesTable').append(result);
}
})
}
[HttpPost]
public ActionResult AddAttribute()
{
var model = new AttributeEntryViewModel();
return PartialView("_AttributeEntryPartial", model);
}