user3667798
user3667798

Reputation: 107

How to find the exceptions / errors when TryUpdateModel fails to update model in asp.net mvc 3

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?

Upvotes: 9

Views: 5293

Answers (1)

StuartLC
StuartLC

Reputation: 107247

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.

Upvotes: 17

Related Questions