user7766809
user7766809

Reputation:

ASP.NET MVC checkbox always false

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.

Upvotes: 10

Views: 17357

Answers (3)

The Professor
The Professor

Reputation: 59

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

Upvotes: 6

Karthik Elumalai
Karthik Elumalai

Reputation: 1612

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

Upvotes: -1

Munzer
Munzer

Reputation: 2318

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

Upvotes: 23

Related Questions