Search code examples
asp.net-mvccheckboxhtml-helper

Html.CheckBox returns false if disabled, even if seleced


Hopefully an easy question for you asp.net mvc gurus:

I have a checkbox, created like this:

<%=Html.CheckBox("MyCheckBox", true, new { disabled = "disabled"})%>

In my action I am checking the value like so:

bool isChecked = form["MyCheckBox"].Contains("true");

I expect this to return true, as it is checked. However the hidden element that gets created has a false value:

<input checked="checked" disabled="disabled" id="MyCheckBox" name="MyCheckBox" type="checkbox" value="true" />
<input name="MyCheckBox" type="hidden" value="false" />

First, is there a way to make the HtmlHelper behave as I expect it should? Or is manually constructing the input/creating my own helper method the only way? (not that this is a big deal...)

Second, can anyone shed some light on why the checkboxes behave this way? Am I incorrect in assuming a disabled checkbox that is ticked should == true? Does a disabled state semantically mean false?


Solution

  • An input field marked with the disabled="disabled" attribute NEVER sends its value to the server. If you want to achieve this you could use the readonly="readonly" attribute which still prevents the user from modifying the value but sends the existing value when the form is submitted.