Removing errors from ModelState in MVC

I wouldn’t normally try to override MVC’s own validation on textboxes etc but occasionally it can be useful. All the things I have seen so far on the Web are pretty messy – turning the ModelState into a dictionary and then iterating through it – and then just removing all the errors associated with that screen control regardless of what the error is. Not very subtle and a bit hacky.

The code below shows a way of doing this in the (slightly contrived but simple) situation where you have a view model with a strongly typed non-nullable DateTime tied to a textbox. This will of course throw an error automatically when trying to submit a blank in the textbox – which is great most of the time. However in a particular context you might want to allow it. Instead of making the DateTime nullable in the view model, and then manually testing for null you could also check for the error in the ModelState and then remove it. Here is how:

public ActionResult Save(MyViewModel model, string btnSave, string btnCancel)
{
       ModelState val;
       if (ModelState.TryGetValue("MyDate", out val) == true)
       {
              if (val.Value.AttemptedValue == "") // Test for the string you are going to allow here              
              {
                        ModelState.Remove(new KeyValuePair<string, ModelState>("MyDate", val));
                        model.MyDate = null; // Set your property to whatever your override is here
              }
       }

      .....
}
 

Obviously the example is a little bit contrived, but the point is that you can use the AttemptedValue property to check for specific entered values – which is useful if you only want to check for a particular value. Also – the TryGetValue method is very useful too, no converting to dictionaries and iterating needed!

About these ads

About Andrew Jerrison
I am a software developer living near Manchester, UK. I work at a UK university creating software for members of the academic staff. In my spare time, amongst my many interests, I am studying via distance learning with De Montfort University.

Leave a Reply

Please log in using one of these methods to post your comment:

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

Follow

Get every new post delivered to your Inbox.

Join 70 other followers

%d bloggers like this: