lukkea
lukkea

Reputation: 3614

ASP.NET MVC2 Html.Checkbox not checking when isChecked=true

I have several checkboxes on a form. Only one of them is checked when it needs to be; all the others are unchecked regardless of whether the isChecked parameter is passed in as either true or false.

The checkboxes are coded like this:

    <%= Html.CheckBox("cbName",Model.checkvalue)%>
    <%= Html.CheckBox("cbName1",Model.checkvalue1)%>

I have stepped through the code and Model.checkValue and Model.checkValue1 are both true, but cbName is not checked and cbName1 is checked (in fact, in my actual app' there are several more CheckBoxes and none are checked -except the second one in the form- although the Model properties are all true in the test I ran).

Has anyone come across this (mis)behavior before & can you let me know where I am going wrong, please? I can't find a similar question anywhere, so I am hoping I am just making a simple error that will be quick to fix...

Upvotes: 0

Views: 2137

Answers (3)

cpoDesign
cpoDesign

Reputation: 9153

what about use different way of rendering the code ( of course you can later simplify this code or create your own helper):

<%
if(Model.checkvalue1){
%>
<%= Html.CheckBox("name", new {checked =checked }) %>
<%}else{%>
<%= Html.CheckBox("name", null) %>
<%}%>

idea 2 make sure that the value you are passing in is boolean: therefore cast is as boolean

 <%= Html.CheckBox("cbName1",(bool)Model.checkvalue1)%>

idea 3 before using the code

<% bool myTempValue = Model.checkvalue1; %>
<%= Html.CheckBox("cbName1",myTempValue)%>

Upvotes: 1

lukkea
lukkea

Reputation: 3614

It was because the underlying data uses a nullable boolean.

I switched the CheckBox to a CheckBoxFor and got the error outlined in this question and this told me that the problem is the fact that the underlying data currently uses a nullable boolean. Since this data type will be switched for a not null boolean once ready I don't need to work around this.

I hope this answer helps someone else.

Thank you for everyone's contributions.

Upvotes: 0

dkl
dkl

Reputation: 3942

There could be some reasons for this behavior:

Is there any query string parameter named cbName in URL of the page? Or, is it a POST request of the form? Query string and form (POST) data take precedence over explicit values set in code.

What browser are you using? FireFox sometimes preserves form data over page reloads. If you check a checkbox and refresh the page, FireFox checks the checkbox again, even when there is no "checked" attribute in HTML input element.

Upvotes: 0

Related Questions