Removing errors from ModelState in MVC
31/05/2011 Leave a comment
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!