ASP.Net MVC3 model binding bug
I've found a wierd scenario that开发者_如何学Python prevents a bool? being posted back to the controller correctly. It's a very specific problem so follow the steps to recreate.
The application must be deployed as a virtual folder in IIS so that instead of /Home/Test the URL is /Virtual/Home/Test.
Home Controller:
[HttpGet]
public ActionResult Test(int? temp, bool? testBool)
{
return View(testBool);
}
/Home/Test View (Razor cshtml):
@model bool?
@{
ViewBag.Title = "Test";
}
@using (Html.BeginForm("Test", "Home", FormMethod.Get))
{
@Html.CheckBox("testBool", Model ?? false, new { onchange = "this.form.submit();" })
@Html.Label(Model == true ? "True" : "False")
}
On post back the bool? doesn't make it to the controller because of the int? before it in the parameter list. This can be solved by putting the bool? before the int? in the parameter list but obviously you shouldn't have to do this. It also works fine if not in a Virtual folder on IIS. The same problem exists if using a POST method too although posting a bool rather than a bool? does work but isn't necessary if not on a virtual folder so shouldn't have to do this either.
Has anyone else experienced this and is there anything that explains why binding fails or is it just a bug in MVC3?
If it is just a bug, does anyone know what are the proper ASP.Net MVC channels for submitting bug reports?
Update:
I've found that if you have any number of nullable variables in the action parameters, only the first one will ever work and all others will fail to be populated. Anyone know if this is by design or a bug?
This article may be of use to you.
Apparently this is still an issue. Thought it would have been fixed by now. One way around this particular bug is to add this to your Application_Start
method.
ModelMetadataProviders.Current = new DataAnnotationsModelMetadataProvider();
Adding that will allow nullable parameters to behave appropriately. I'm surprised this bug still exists as it was known as of RC2 in December.
The difference between the route optional parameters in the article by haacked is that, in your example, routing isn't the problem. In this case you're posting (or querystring) data and that isn't populating your nullable action parameters properly. I've checked the mvc3 source and don't see why this should be a problem as debugging it it seems to work properly and stepping through the source results in the expected behavior. I'm fairly certain this hasn't been fixed even though Scott Guthrie said it should be by now...
精彩评论