Posted by: Cirilo Meggiolaro | 04/16/2009

Tip of the day #184 – ASP.NET MVC – UI Validation

ASP.NET MVC provides some objects to help you out on UI validation. What is important to know?

ModelState Object

The ModelState is a dictionary available on the base Controller class that stores the state and additional information about the model. Basically when a post happens you can perform your checks and if something goes wrong you may add an item to the ModelState dictionary and this information will be available to be used by the View to display a summary of inconsistencies for example. The ModelStateDictionary has several methods to add entries to it:

  • void Add(KeyValuePair<string, ModelState> item);
  • void Add(string key, ModelState value);
  • void AddModelError(string key, Exception exception);
  • void AddModelError(string key, string errorMessage);

The following code shows an existing method that validates the logon information. When you create a new ASP.NET MVC web application this method is available by default on AccountController class. The method checks both parameters (username and password) and if the parameters are not valid a new entry is added then to the ModelState dictionary. The last check is a try to logon. If the logon fails an entry will be added also. Finally the method retrieves the value of the Boolean property called IsValid. If you add an entry to the dictionary the value of the property will be false. Otherwise it will return true.

private bool ValidateLogOn(string userName, string password)
{
    if (String.IsNullOrEmpty(userName))
    {
        ModelState.AddModelError(“username”, “You must specify a username.”);
    }

    if (String.IsNullOrEmpty(password))
    {
        ModelState.AddModelError(“password”, “You must specify a password.”);
    }

    if (!MembershipService.ValidateUser(userName, password))
    {
        ModelState.AddModelError(“_FORM”, “The username or password provided is incorrect.”);
    }

    return ModelState.IsValid;
}

You may have noticed that the AddModelError method is receiving a key and a message as parameters. The key is the name of the control to “bind” the message to it and the message contains the text that will be displayed beside the control and on a summary if you add it. To better understand how all these items are related let’s take a look at the Logon View. Check the name of the textboxes. They match with the keys added to the dictionary on the previous code snippet.

<%= Html.ValidationSummary(“Login was unsuccessful. Please correct the errors and try again.”) %>

<% using (Html.BeginForm()) { %>
     <div>
        <fieldset>
            <legend>
Account Information</legend>
            <p>
                <label for=”username”>
Username:</label>
                <%= Html.TextBox(“username”) %>
                <%= Html.ValidationMessage(“username”) %>
            </p>
            <p>
                <label for=”password”>
Password:</label>
                <%= Html.Password(“password”) %>
                <%= Html.ValidationMessage(“password”) %>
            </p>
            <p>
                <input type=”submit” value=”Log On” />
            </p>
        </fieldset>
    </div>

<% } %>

Helper controls

On the previous section you saw some dynamic code invoking methods available under the Html class:

ValidationSummary: The ValidationSummary is responsible for displaying a bullet list with all items available on the ModelState dictionary. The syntax is pretty straightforward. You just need to pass a message as parameter:

<%= Html.ValidationSummary(“Login was unsuccessful. Please correct the errors and try again.”) %>

ValidationMessage: It generates a <span> tag besides the control that has the same name than the one passed as parameter. Different from the RequiredFieldValidator available on regular ASP.NET applications, the ValidationMessage does not execute the check of content typing but it is used for display a message only.

<%= Html.ValidationMessage(“username”) %>

If you execute the default ASP.NET MVC Web Application and hit the Log On button without entering the username and password, you will get the following view:

Picture 1 - UI validation output

Picture 1 - UI validation output

Another option you have is to define a message using a different ValidationMessage overload:

<%= Html.ValidationMessage(“username”, “*”) %>

This overload is useful when your post method is waiting for an instance of the model object that the View inherits from. In this scenario if a value cannot be bound to a property on the model object, the ModelState will be invalid so you can retrieve the same object to the View that will display the default messages.

public ActionResult Create()
{
    return View(new MyViewModel());
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(MyViewModel model)
{
    if (!ModelState.IsValid)
        return View(model);

    return View(new MyViewModel());
}

The View will display some similar to the following:

Picture 2 - UI validation with pre binding

Picture 2 - UI validation with pre binding

Tomorrow we are going to check in more details how to work with the Html Helpers and how to create your own helper.

Stay tuned!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: