ASP.NET MVC UI Error Handling - ModelState and AddModelError

Previous tutorial: ModelBinders in ASP.NET MVC - ComplexModelBinder Quick Tip

I am still sinking my teeth into ScottGu's post on ASP.NET MVC Preview 5 and absolutely lovin' the new ModelState Property on ViewData that can help the UI developer in re-displaying error messages on the view. The trick is to use the ModelState.AddModelError method during input validation to notify the View that there is an error in the input.

For example, when the following form is posted by the user I am going to automatically tell the user that the phone is indeed incorrect:

 

ModelState.AddModelError

 

A couple of things in play here.

First, the Save Action on the Customers Controller has to notify the ModelState that there is an error in the input via the ViewData.ModelState.AddModelError Method:

 

public ActionResult Save(FormCollection form)
{
    ViewData.ModelState.AddModelError("Phone",
        form["Phone"], "Dude, Phone is wrong!");
    return View(form);
}

 

Assume I am doing some validation, but the method of validation is unimportant. The key is calling the AddModelError Method and passing:

  • The Key, which is essentially the name of the control on the form - “Phone“
  • The Attempted Value for phone that was erroneous - form[“Phone“]
  • The Exception or Error Message to display on the View - “Dude, Phone is wrong!“

The other piece of the puzzle is including a

  • <%= Html.ValidationMessage("Phone") %>

in the view to display the error message passed into the ModelState. Just add it next to the control on the form.

Notice the red border around the Phone TextBox. Check the Site.css in your ASP.NET MVC Template and you will find a new CSS Class

 

.input-validation-error
{
    border: 1px solid #ff0000;
    background-color: #ffeeee;
}

 

This class is added dynamically by the View to the TextBox Control when you add an error via ModelState.AddModelError.

Very cool stuff!

 

posted on Sunday, September 07, 2008 9:29 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices