tags:

views:

1372

answers:

1

I have an ASP.NET MVC project with a form. In the Action method that handles the POST verb I have a custom IModelBinder implementation that is binding the form data to my model instance. If there are errors I am using bindingContext.ModelState.SetAttemptedValue() and bindingContext.ModelState.AddModelError() to persist the submitted value and error message to the ModelState.

This works great and I can see the expected behavior occurring on my input controls that are rendered with Html.TextBox() (which calls through to Html.InputHelper()). When I use Html.CheckBox() (which also calls through to Html.InputHelper()) the state of my CheckBox is NOT output to th <input /> tag.

It seems to me like the Html.InputHelper() method is not using the AttemptedValue from the ModelState for input fields of type CheckBox.

Here is the code from ASP.NET MVC Html.InputHelper() method.

Why is it that the CheckBox attemptedValue is not output to the input tag. Is there something I am missing here or do I need to manually handle this case by checking the ModelState and setting the tag attribute myself?

Update 11/09
Here is the call to HtmlHelpers that I am using to output the CheckBox:

<%= Html.CheckBox("IsDerived") %>

And here is the call that I am using to register the Attempted Value:

string isDerivedRequestValue = !string.IsNullOrEmpty(bindingContext.HttpContext.Request["IsDerived"]) ? bindingContext.HttpContext.Request.Form.GetValues("IsDerived") [0] : null;
bindingContext.ModelState.SetAttemptedValue("IsDerived", isDerivedRequestValue);
+1  A: 

I'm not sure if this is the best way to solve the problem or not, but since the Html.InputHelper() method is not checking the AttemptedValue for CheckBox controls I added the following to my controller which embeds the proper value from the ModelState into ViewData and seems to do the trick quite well.

ViewData["IsDerived"] = ViewData.ModelState.ContainsKey("IsDerived")
                           ? bool.Parse(ViewData.ModelState["IsDerived"].AttemptedValue)
                           : false;

Make sure you are not explicitly setting the isChecked parameter value when you call Html.CheckBox() as that will override any value stored in ViewData.

spoon16