Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 856
user3667798 Avatar asked Jun 03 '14 04:06

user3667798


People also ask

How do I get ModelState errors in my controller?

You can use SelectMany function c# to get error message from modelstate mvc. It will generate error message string it contains modelstate errors; we can return as json and display in html element. You have to define validations inside the class as per requirement.

How do I show ModelState error in view?

To pass error to the view we can use ModelState. AddModelError method (if the error is Model field specific) or simply ViewBag or ViewData can also be used.


1 Answers

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.

like image 79
StuartLC Avatar answered Sep 21 '22 19:09

StuartLC