views:

1616

answers:

3

I have this annoying issue with the checkbox created using the Html.Checkbox extension method. Apparently the state of the checkbox is not saved in case of a postback (due to a form validation error). Delving into the MVC code itself (System.Web.Mvc.Html.InputExtensions) I found out that the 'checked' property is determined by calling 'htmlHelper.EvalBoolean(name)'. This method looks for the key (specified in the name argument) of the ViewData itself. The problem is that the value of the checkbox is actually located in the ModelState. Calling 'htmlHelper.GetModelStateValue(name, typeof(bool))' would return the expected result.

Is this a flaw in the checkbox implementation ?

A: 

Remember that the ideaology behind MVC is to move the web back to the way it was a few years ago. You are not supposed to have postbacks on a page without using something like AJAX. As such, most controls that you are used to maintaining their own state will no longer do.

Have you thought of using AJAX to try solve this problem? That way you can have your postbakc and maintain the state of the control?

FailBoy
Client side validation is 'Nice to have' but isn't satisfactory. In the end most sites need to validate on the server side
Harry
A: 

This issue was posted on codeplex and will be fixed/supported in the MVC RTM. In the meantime, this is a nice workaround.

A: 

I posted another workaraound here:

How to maintain state of Html.CheckBox() in ASP.NET MVC

Thomas Eyde