This was working fine in MVC 3, I'm not sure if this is an intended change or not.
In MVC4, the model binder cannot properly bind a Dictionary<> if the form was submitted with no values. Consider the following controller action:
[HttpPost]
public void Index(Dictionary<int, bool> values, FormCollection form)
{
}
In MVC3 if this action was called with no values, the dictionary would simply contain 0 entries. In MVC4 if this action is called with no values, it throws an exception: "Specified cast is not valid."
Changing the controller action to the following produces the expected result as it was in MVC3:
[HttpPost]
public void Index(FormCollection form)
{
var values = new Dictionary<int,bool>();
this.UpdateModel(values, "values");
}
I have attached a solution which demonstrates the problem.
Comments: This just bit me again in another project... <sigh>
In MVC4, the model binder cannot properly bind a Dictionary<> if the form was submitted with no values. Consider the following controller action:
[HttpPost]
public void Index(Dictionary<int, bool> values, FormCollection form)
{
}
In MVC3 if this action was called with no values, the dictionary would simply contain 0 entries. In MVC4 if this action is called with no values, it throws an exception: "Specified cast is not valid."
Changing the controller action to the following produces the expected result as it was in MVC3:
[HttpPost]
public void Index(FormCollection form)
{
var values = new Dictionary<int,bool>();
this.UpdateModel(values, "values");
}
I have attached a solution which demonstrates the problem.
Comments: This just bit me again in another project... <sigh>