Is there a use for the overload of AddModelError() that takes an Exception as a parameter?
If I include the following code in my controller:
ModelState.AddModelError( "", new Exception("blah blah blah") );
ModelState.AddModelError( "", "Something has went wrong" );
if (!ModelState.IsValid)
return View( model );
And the following in my view:
<%= Html.ValidationSummary( "Please correct the errors and try again.") %>
Then only the text "Something has went wrong" is displayed in the error summary.
AddModelError(String, String)Adds the specified error message to the errors collection for the model-state dictionary that is associated with the specified key.
ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process.
The ModelState has two purposes: to store the value submitted to the server, and to store the validation errors associated with those values.
ModelState.AddModelError method accepts two parameters. Key – First parameter, if empty shows error written in the 2nd parameter at place where @Html. ValidationSummary(true, "", new { @class = "text-danger" }) is written in the view.
Checking the source ModelError accepts both and the usage is for model type conversion failures.
In this particular case it's to go down the exception tree and grab inner exceptions when necessary to find the actual root error rather than a generic top level exception message.
foreach (ModelError error in modelState.Errors.Where(err => String.IsNullOrEmpty(err.ErrorMessage) && err.Exception != null).ToList()) {
for (Exception exception = error.Exception; exception != null; exception = exception.InnerException) {
if (exception is FormatException) {
string displayName = propertyMetadata.GetDisplayName();
string errorMessageTemplate = GetValueInvalidResource(controllerContext);
string errorMessage = String.Format(CultureInfo.CurrentCulture, errorMessageTemplate, modelState.Value.AttemptedValue, displayName);
modelState.Errors.Remove(error);
modelState.Errors.Add(errorMessage);
break;
}
}
}
As you can see it's looping through the exception in the ModelError to find a FormatException. This is the only real reference to this I can find in both MVC 2 and MVC 3.
That said it's probably unnecessary for regular use.
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