9

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.

Draken
  • 3,134
  • 13
  • 34
  • 54

3 Answers3

21

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" />

Munzer
  • 2,216
  • 2
  • 18
  • 25
5

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" />
The Professor
  • 49
  • 1
  • 2
-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

Karthik Elumalai
  • 1,574
  • 1
  • 11
  • 12
  • 3
    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 –  May 23 '17 at 22:50