开发者

UpdateModel raise exception

开发者 https://www.devze.com 2023-01-22 12:45 出处:网络
I have a strong typed view model and a MetaData partial class which has annotation attributes on required fields and field type.The Create.aspx view page has a form when submitted will execute Create

I have a strong typed view model and a MetaData partial class which has annotation attributes on required fields and field type. The Create.aspx view page has a form when submitted will execute Create method in the controller. When the user submit the form without all the required fields entered, upon reaching UpdateModel() line an exception is thrown. However, none of the error messages specified in the annotated fields is shown. Instead, the execution iterate through the RuleViolation() and landed at the most generic exception message. Thus, the user does not know that some required fields are not entered. If I define the checking if empty of required fields in the RuleVilolation() method then it is not DRY. Does anyone know why the error messages are not shown from the MetaClass? Thank you.

///Controller method
[AcceptVerbs(HttpVerbs.Post)]
开发者_C百科[ValidateInput(false)]
public ActionResult Create(string id, [Bind(Prefix = "Transfer")]TransferFormViewModel newTransferViewModel, string cancel)
{
  ....
  if (ModelState.IsValid)
  {
      Transfer newTransfer = new Transfer();

      if (ModelState.IsValid)
      {
        try
          {
            Person person = base.ApplicaitonRepository.GetPerson(intID);
            UpdateModel<Transfer>(newTransfer, "Transfer");
            .....
          }
        catch (Exception ex)
          {
            newTransfer.MiscException = ex;
            HelpersLib.ModelStateHelpers.AddModelErrors(this.ModelState, newTransfer.GetRuleViolations());
          }
      }
   }
   return View(new TransferFormViewModel(base.ApplicaitonRepository, newTransfer));
}

///partial domain objec class
[MetadataType(typeof(TransferMetaData))]
public partial class Transfer
{
  public IEnumerable<RuleViolation> GetRuleViolations()
  {
    ....
  }
}

///MetaData class
class TransferMetaData
{
[Display(Name="List Type")]
public int ListType { get; set; }

[Required(ErrorMessage = "Notification Date/Time is required."), Display(Name = "Notification Date/Time")]
        public DateTime AddedToListDate { get; set; }

[Required(ErrorMessage="Admit Date/Time is required."), Display(Name="Admit Date/Time")]
...
}


Do you have <%= Html.ValidationSummary() %> somewhere in your view?

What entries are in your ModelState?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号