Make a checkbox checked or unchecked based on the value?
If you do not want to use @Html.CheckBoxFor for whatever reason and you'd like to stick to
<input type="checkbox">
then this is what I found to be the best way to do it:
<input @(Convert.ToBoolean(Model.YourPropertyHere) == true ? "checked='checked'" : string.Empty) type="checkbox" />
The code that @Yasser provided above:
checked="@(required ? "checked" : "")"
Did not work for me because it was still adding the checked attribute to the element, and setting checked="" will still render the check box as checked, which was not the desired output, instead if you wrap the whole statement into a razor block like so:
@(Convert.ToBoolean(Model.YourPropertyHere) == true ? "checked='checked'" : string.Empty)
you will get the desired results.
if(condition = true)
{
@Html.CheckBoxFor(x => x.Test, new { @checked = "checked" })
}
else
{
@Html.CheckBoxFor(x => x.Test)
}
Hope this helps :)