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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With