All I want to know is the proper syntax for the Html.CheckBoxFor
HTML helper in ASP.NET MVC.
What I'm trying to accomplish is for the check-box to be initially checked with an ID value so I can reference it in the Controller to see if it's still checked or not.
Would below be the proper syntax?
@foreach (var item in Model.Templates)
{
<td>
@Html.CheckBoxFor(model => true, item.TemplateId)
@Html.LabelFor(model => item.TemplateName)
</td>
}
By default, the below code will NOT generate a checked Check Box as model properties override the html attributes:
Instead, in your GET Action method, the following needs to be done:
The above will preserve your selection(If you uncheck the box) even if model is not valid(i.e. some error occurs on posting the form).
However, the following code will certainly generate a checked checkbox, but will not preserve your uncheck responses, instead make the checkbox checked every time on errors in form.
Above code would generate a checked check Box at starting and will also preserve your selection even on errors in form.
None of the above answers worked for me when binding back on POST, until I added the following in CSHTML
I was looking for the solution to show the label dynamically from database like this:
So none of the above solution worked for me so I used like this:
In this way when user will click on label, checkbox will be selected.
Might be it can help someone.
I had trouble getting this to work and added another solution for anyone wanting/ needing to use FromCollection.
Instead of:
Format html helper like so:
Then in the viewmodel/model wherever your logic is:
I was having a problem with ASP.NET MVC 5 where CheckBoxFor would not check my checkboxes on server-side validation failure even though my model clearly had the value set to true. My Razor markup/code looked like:
To get this to work, I had to change this to:
Place this on your model:
And this in your cshtml:
Which will output this:
If you click on the checkbox or the bold label it will check/uncheck the checkbox