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

asp.net-mvc, asp.net-mvc-3

Solution

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.

Problem

``` 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?

Original source

Related problems