11

I made an asp.net website, but the checkbox is always false. Why is this so?

Model:

 public string Username { get; set; }
 public string Password { get; set; }
 public bool Remember { get; set; }

CSHTML:

<div class="form-group">
    @Html.Label("Remember me?")
    @Html.CheckBoxFor(m => m.Remember)
 </div>

The Remember property is always false, if the checkbox is checked then Rememberis still false.

2
  • 2
    Do you ever set it to true? Commented May 23, 2017 at 12:34
  • 1
    No, if the checkbox is checked then also false. Commented May 23, 2017 at 12:36

3 Answers 3

24

I got the same issue, I fixed it by writing html checkbox tag, giving it the name same as property name, and value = true, if the checkbox is not checked no need to worry as it won't be submitted anyway, in your case this will be it

<input type="checkbox" name="Remember" value="true" />

Sign up to request clarification or add additional context in comments.

2 Comments

The is the only way I can see to do it. CheckBoxFor just plain doesn't work. Who knows if it ever did.
I just try this on Chrome. Updating the form send true on the saving even if you don't check the checkbox.
6

With Razor, I had the same problem. What worked for me was taking off the value="xxx" tag. Then it functioned normally.

Does not work:

 <input class="form-check-input" value="true" asp-for="Answer.aIsCorrect" />

Works:

 <input class="form-check-input" asp-for="Answer.aIsCorrect" />

Comments

-1

The first parameter is not checkbox value but rather view model binding for the checkbox hence:

@Html.CheckBoxFor(m => m.SomeBooleanProperty, new { @checked = "checked" }); The first parameter must identify a boolean property within your model (it's an Expression not an anonymous method returning a value) and second property defines any additional HTML element attributes. I'm not 100% sure that the above attribute will initially check your checkbox, but you can try. But beware. Even though it may work you may have issues later on, when loading a valid model data and that particular property is set to false.

Source and additional info: https://stackoverflow.com/a/12674731/3397630

Hope it will helpful for you ,kindly let me know your thoughts or feedbacks

Thanks Karthik

1 Comment

That is exactly what OP already has! - a bool property named Remember and @Html.CheckBoxFor(m => m.Remember) (and setting `new { @checked = "checked" } is pointless - its the value of the property which determines if its checked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.