我正在创建新记录并将新记录返回到视图。
我的观点:
@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>
}
对@ Model.Contact.ID的引用工作正常并显示:
ContactID = XX
然而,渲染的隐藏字段如下所示:
<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">
值为0.显示正确ID的事实表明我的控制器正在返回正确的值。为什么视图没有正确设置隐藏字段的值?
感谢。
更新: 这是我的控制器动作:
[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);
}