Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of ModelState.AddModelError with exception parameter

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.

like image 681
David Gardiner Avatar asked Sep 22 '10 02:09

David Gardiner


People also ask

What does ModelState AddModelError do?

AddModelError(String, String)Adds the specified error message to the errors collection for the model-state dictionary that is associated with the specified key.

What is the purpose of ModelState IsValid property?

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.

What is the point of checking ModelState?

The ModelState has two purposes: to store the value submitted to the server, and to store the validation errors associated with those values.

What is ModelState AddModelError in MVC?

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.


1 Answers

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.

like image 50
Buildstarted Avatar answered Sep 22 '22 07:09

Buildstarted