Forgetting To Use Nullable Action Method Parameters

I am thinking that this is something that people will do fairly frequently. I do it all of the time. You would think I would learn.

On a form post, if the value for a field is put into the signature of the action method, that parameter must be nullable. This means that it needs to be a nullable type (like int? or a reference type like a class). This, of course, means that the controller action needs to handle the possibility of a null value. The following material for the sample below is from the Tigers Assault the Monkeys sample used for one of the getting started tutorials. First, the not-so-obvious error message that you get goes something like this: "The parameters dictionary contains a null entry for parameter 'numberOfTigersSent' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult TigersAssaultTheMonkeys(Int32)' in 'HowMVCWorks.Controllers.ZooController'. To make a parameter optional its type should be either a reference type or a Nullable type. Parameter name: parameters".

The error screen you will get will look a lot like this:

Screenshot of the error you get when you don't use a nullable type for a parameter to a post method and the value is invalid.

For an example of how this works, take a look at the Tigers Assault the Monkeys sample. Remember: always make your controller parameter types nullable!

Speak Your Mind!

Have something to say? Find a grammatical mistake? Think I said something incorrect? Don't like my perspective? Hate my color scheme? Whatever it is, you can let me know. I would appreciate it if you did.