9
if (!TryUpdateModel<Event>(evt))
{ 
   // ... I need to retrieve the errors here
}

Sometimes, TryUpdateModel fails to update model. I am not able to find reason and exception?

StuartLC
  • 104,537
  • 17
  • 209
  • 285
user3667798
  • 107
  • 1
  • 5

1 Answers1

17

As per the other TryXXX paradigm methods (e.g. TryParse), the TryUpdateModel method returns a bool indicating whether the model was updated successfully or not.

TryUpdateModel updates the ModelState dictionary with a list of errors. If TryUpdateModel fails (as per the bool return), you can iterate these as follows:

 var model = new ViewModel();
 var isSuccess = TryUpdateModel(model);

 if (!isSuccess)
 {
     foreach (var modelState in ModelState.Values)
     {
        foreach (var error in modelState.Errors)
        {
           Debug.WriteLine(error.ErrorMessage);
        }
     }
 }

Otherwise, if you want a hard exception, then use UpdateModel instead.

Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285