Wednesday, February 15, 2012

MVC3 controller action model argument is null

After re-naming some controller action arguments I recently discovered a method that was previously working, unexpectedly returning null for the controller action argument. The action used the default model binder pulling data from both the query string and route values. Consider the following code:

public class Search
{
  public string Name {get;set;}
  public string Query {get;set;}
}
public ActionResult Results(Search query)
{
....
}
....
///results/{Name}
....
///results/monkeys?Query=12-of-them-jumping


The default model binder rather than binding to the object is trying to take your "Query" and plug it into the action method as an argument. Since string is not "Search" it results in a null value, the short lesson to take from this puzzle is to avoid naming properties on your object the same name as arguments you are passing into the controller action.