Tag Archives: asp.net

ASP.NET ModelState – keys are changed behind your back

Summary

Today I came across a strange behaviour within the ModelState property of the APIController .

In summary I discovered that the keys used by the developer get changed by ASP.Net … but only sometimes !

Background

To paraphrase the doco the ModelState dictionary is used to “represent the state of an attempt to bind a posted form to an action method, which includes validation information”.

One straightforward place this is seen is where an API request has provided a value which can’t be used to populate the relevant property of the underlying model. The resultant error is reflected in the contents of the ModelState property.

As well as this type of ‘automatic’ population of ModelState it’s possible use the AddModelError method to add your own errors to the dictionary like this :

ModelState.AddModelError("inputSample.StartDate", "Some sort of validation error");

Weirdness (or should I say ‘WeIrdNeSs’ ?)

The behaviour I saw today concerns the way the key used as the first argument to AddModelError gets manipulated in what I consider to be a rather confusing manner.

In the example above the underlying model had a property of ‘StartDate’ and so everything worked as you might have expected.

If however you use a key which is unrelated to any property of the model, eg ‘Foo’, you can still add the item to ModelState and it will exist in the underlying dictionary under the key used, like this :

ModelState.AddModelError("inputSample.Foo", "Some sort of validation error");

Where things get strange, at least in my view, is if you use a string which happens to match a property name if both your proposed key and the a Model property match when both are lower cased. For instance ‘HairColour’ might be a Model property name and a key might be used of ‘HaIrCoLoUr’ .

In that situation something in the ASP.NET plumbing decides that you didn’t really mean to use a key of ‘HaIrCoLoUr’ and instead meant to use ‘HairColour’.

I don’t like this behaviour because I really don’t like ‘magic’ going on in the background – others may feel differently.