Displaying Error messages in ASP.Net MVC
Ok so as I implemented my blog software for this site I had to figure out a way to display error messages to the user. For example if I had a required field that the user didn't fill in I wanted to alert the user to fill in that field.
My first thought was that MVC should have something to handle this, so I was going to start there. Unfortunately, after looking around a lot online, I realized that at the time MVC didn't have that. So what to do?
Well I have a base class for all of my Models, can I put something in there? Just about every screen might have a need to return an error message so why not? Ok, I had a place to put my errors, but how would I actually implement them?
I decided upon using a Dictionary to hold the messages. The key to the dictionary would be the name of the control that the error message was associated with, and the value was the error message itself. Then in my page code I checked that dictionary for any error messages and displayed them as neccessary.
Does any of this sound familiar? It should, its pretty much what ended up coming out in RC5 of ASP.Net MVC.
When RC5 came out MS added error support to their ViewData class. Now when you are in a controller class you can add an error message to the ViewData object instance by calling AddModelError. That method takes two parameters a key to identify the error message. This is usually the name of the control associated with the error, but it could be anything. The second parameter is the error message itself.
For example
public ActionResult Register(string userName, string password)
{
if (userName == "")
{
ModelState.AddModelError("userName", "Please enter a user name.");
}
...
}
They also added another method IsValid to ViewData, this method will return true if there are no errors stored in ViewData, but false if there are errors. Essentially you want to use this after checking your inputs, and before you act upon them to make sure you dont' have any problems. It saves you from having to track this yourself somehow.
Then finally you display it in the page using the following code.
<td>< %= Html.ValidationMessage("userName") % ><td>
The resulting message displayed can even by styled by you. Ifyou add the following definition to your css file and configure as you like is all you need to do.
.input-validation-error
{
}
That's it, simple as that. I really like it, its quick and easy to use, clean to implement, and most importantly it fits in with what I had before (okay maybe thats not ths most important thing to everyone, but it was to me)