My MVC 2 server side validation rules are not firing

Problem

I am using a Form Collection in my [HttpPost] action of my controller and my ModelState.IsValid is not being set correctly for invalid input.

Solution

Add a call to UpdateModel or TryUpdateModel which will populate your model and fire the validation rules setting the ModelState.IsValid property correctly.

Code

In the incorrect implementation below ModelState.IsValid is always true.

[HttpPost]
public ActionResult EditProfile(FormCollection values)
{
  
ProfileCommon profile = new ProfileCommon
();
   profile
= profile.GetProfile(User.Identity.
Name);
  
  
if(ModelState.
IsValid)
   {
      profile
.DisplayName =
values["DisplayName"];
      profile
.
Save();
     
return
RedirectToAction("Index", "Home");
   }
  
else
//Show validation errors
     
return
View();
}

In the correct implementation below ModelState.IsValid gets set by the call to TryUpdateModel.

[HttpPost]
public ActionResult EditProfile(FormCollection
values)
{
  
ProfileCommon profile = new ProfileCommon
();
   profile
= profile.GetProfile(User.Identity.
Name);

  
//Fill my model from the collection and validates it.
  
TryUpdateModel(profile, values);

  
if(ModelState.
IsValid)
   {
      profile
.
Save();
     
return
RedirectToAction("Index", "Home");
   }
  
else
//Show validation errors
      return
View();
}
 

 

 

Explanation

The built in server side validation for MVC 2 will only work if your action accepts the a Model object as a parameter. This causes MVC to create the model object and automatically map the incoming form input values to it.  As part of this process, it will also check to see whether the DataAnnotation validation attributes for the model are valid.  If everything is valid, then the ModelState.IsValid check within our code will return true.

When your action accepts a FormCollection this does not happen therefore, the DataAnnotation validation attributes are never evaluated and the ModelState.IsValid is never set.  We can correct this issue by simply performing  those steps ourselves.  MVC 2 provides functions that we can use to do this (UpdateModel and TryUpdateModel).  The difference is Update will throw if there is a validation error whereas TryUpdate will simply set the IsValid to false.

An added benefit of using the UpdateModel is that an empty model will be populated with all the values from the form collection for you.

 

Comments are closed