I’ve got a POCO that I’m using as an argument to an action in MVC3. Something like this:
My Type
public class SearchData
{
public string Property1 { get; set; }
public string Property2 { get; set; }
public string Property3 { get; set; }
}
My Action
public ActionResult Index(SearchData query)
{
// I'd like to be able to do this
if (query == null)
{
// do something
}
}
Currently, query is passed as an instance of SearchData with all of the properties as null. I’d prefer that i get a null for query so I can just do the null check that I have in the above code.
I could always look at ModelBinder.Any() or just the various keys in ModelBinder to see if it got any of the properties for query, but I don’t want to have to use reflection to loop over the properties of query. Also, I can only use the ModelBinder.Any() check if query is my only parameter. As soon as I add additional parameters, that functionality breaks.
With the current model binding functionality in MVC3, is it possible to get the behavior of returning null for POCO argument to an action?
You’ll need to implement a custom modelbinder to do this. You can just extend
DefaultModelBinder.Specific Implementation
This is the actual implementation of the binder that will return null for the model if all of the properties are null.
Adding this as a binder in global.asax