在我们的 ASP MVC 3 站点中,我们希望用户能够输入一个不完整的表单,将该记录保存到数据库中,然后再返回到该表单。如果输入错误的字段,我们希望在用户点击保存时出现这些错误消息。
但是,特定于出生日期字段的问题正在发生。如果用户输入了错误的日期,例如14/01/2011
,当用户点击保存并且模型对象返回到控制器操作时,出生日期将显示为空白。然后它不符合if (ModelState.IsValid)
条件,不保存到数据库,并被发送回具有空白出生日期的视图。
有没有办法允许用户在此字段中输入错误的日期,保留该值并使用该值和通常由模型生成的错误消息返回视图?由于我们使用的是 jQuery 输入掩码,因此输入的值将始终为数字并采用 MM/DD/YYYY 格式。
模型
[DisplayName("Date of Birth")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Birthdate { get; set; }
控制器
[HttpPost]
public ActionResult Edit(Monet.Models.AgentTransmission agenttransmission)
{
//Date of birth field is null right here in 'agenttransmission' object if
//user enters incorrect value/date
//redirect if security is not met.
if (!Security.IsModifier(User)) return RedirectToAction("Message", "Home", new { id = 1 });
//Tax Id security
ViewBag.FullSSN = Security.IsFullSsn(User);
try
{
agenttransmission = AgentTransmissionValidator.ReformatFields(agenttransmission);
ViewBag.ErrorMessage = AgentTransmissionValidator.ValidateAgent(agenttransmission);
if (ModelState.IsValid)
{
//Whole bunch of code to determine if input is complete/incomplete
//Save the record
db.Entry(agenttransmission).State = EntityState.Modified;
db.SaveChanges();
} //end if model state valid
}
catch (DbEntityValidationException dbEx)
{
ViewBag.ErrorMessage = "An error has occurred, we apologize for the incovenience. IT has been notified and will resolve the issue shortly.";
SendEmail.ErrorMail(Common.ErrorCheck.CombineDbErrors(dbEx));
}
catch (Exception ex)
{
ViewBag.ErrorMessage = ErrorCheck.FriendlyError(ex);
SendEmail.ErrorMail(ex);
}
return View(agenttransmission);
}
看法
<div class="M-editor-label">
@Html.LabelFor(model => model.Birthdate)<span class="req">*</span>
</div>
<div class="M-editor-field">
@Html.EditorFor(model => model.Birthdate)
@Html.ValidationMessageFor(model => model.Birthdate)
</div>