I'm creating a new record and returning the new record to the view.
My view:
@using (Ajax.BeginForm((string)ViewBag.EntityControllerUpdateAction, "Contacts",
new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "contactForm",
OnComplete = "$('#contacts').find('.notSaving').hide();"
},
new { @class = "formEntity clearfix" }))
{
<div id="contactForm">
ContactID = @Model.Contact.ID
@Html.HiddenFor(model => model.Contact.ID, new { @class = "entityID" })
</div>
}
The reference to @Model.Contact.ID is working fine and displays:
ContactID = XX
However the rendered hidden field looks like this:
<input class="entityID" data-val="true" data-val-number="The field ID must be a number." data-val-required="The ID field is required." id="Contact_ID" name="Contact.ID" value="0" type="hidden">
The value is 0. The fact that the correct ID is displayed demonstrates that my controller is returning the correct value. Why doesn't the view set the value of the hiddenfield correctly?
Thanks.
UPDATE: Here's my controller action:
[HttpPost]
public ActionResult UpdateContact(ContactVM Entity)
{
try
{
if (ModelState.IsValid)
{
if (Entity.Contact.ID == 0) // New entity
repo.Create<Contact>(Entity.Contact);
else
{
Entity.Contact.State = Entity.Contact.State.ToUpper();
repo.Update<Contact>(Entity.Contact);
}
repo.Save();
}
}
catch (DataException)
{
//Log the error (add a variable name after DataException)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
return PartialView("~/Views/Contacts/_ContactForm.cshtml", Entity);
}