[ASP.NET MVC] Model Validation (2) – Controller

This is the second part of the MVC validation feature. In the last post, I explained what the Attributes for model classes are. Now let’s find out how you can check whether a model is valid or not in a Controller.

1. Validating a Model

When you have set the all validation attributes in a model class and add input controls as well as validation messages for a view, you are almost done.

Actually, your validation code already works in a client and a server. But you need to always validate data before saving them to a file or a database.

In a controller action method, you can check whether the model data have passed all validation checks using the “ModelState.IsValid” property.

public ActionResult Edit(Person p)
{
  if (ModelState.IsValid)
  {
    // save it ...
  }
}

2. Validating a Model Explicitly

You know the validation logic should be located in the model class. But you might need to add additional checking logic in a controller.

The “ModelState” property has all information about validating a form data. You can directly validate each field and mark the errors.

  • public ModelStateDictionary ModelState { get; }

The “System.Web.Mvc.ModelStateDictionary” has the following properties:

  • public ICollection<string> Keys { get; }
  • public ICollection<ModelState> Values { get; }
  • public bool IsValid { get; }

and methods:

  • void AddModelError(string key, string errorMessage)
  • public bool IsValidField(string key)

The “ModelState” is a dictionary of (string/ModelState). You can get an individual “ModelState” object for investigation but you can just use the methods provided by  the “ModelStateDictionary” class.

public class Person
{
  public string Name { get; set; }
  public int Age { get; set; }
}
public class PersonController : Controller
{
  public ActionResult Edit()
  {
    Person p = new Person { Name = "Homer Simpson", Age = 40 };
    return View(p);
  }

  [HttpPost]
  public ActionResult Edit(Person p)
  {
    if (string.IsNullOrEmpty(p.Name))
      ModelState.AddModelError("Name", "Person's name cannot be empty");

    if (ModelState.IsValidField("Age") && p.Age < 0)
      ModelState.AddModelError("Age", "Person's age cannot be negative");

    if (ModelState.IsValid)
    {
      // save it ...
    }
    return View(p);
  }
}

3. Model-Level Errors

So far we have only deal with errors of each property. What if you need to validate data using two or more properties. If so, the errors do not belong to a single property. They are called “model-level” errors.

Look at the following example. Homer Simpson cannot be less than 35. So you need 2 pieces of information: Name and Age. If you do provide an empty string to the key parameter of the “AddModelError“, it becomes a model-level error.

[HttpPost] public ActionResult Edit(Person p)
{
  if (p.Name == "Homer Simpson" && p.Age < 35)
  {
    ModelState.AddModelError("", "Homer Simpson cannot be less than 35"); // model-level error
  }
}

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s