How can we make a checkbox checked or unchecked programatically based on the value? That is to say, for a particular user if the value is true, the checkbox should be checke
if(condition = true)
{
@Html.CheckBoxFor(x => x.Test, new { @checked = "checked" })
}
else
{
@Html.CheckBoxFor(x => x.Test)
}
Hope this helps :)
If you want to check/uncheck check box value in code-behind, you have to include an ID and runat server attributes in your check box tag.
<checkbox Id="chk" runat="server" class="chkbox"/>
code-behind:
if(yourcondition==true)
chk.checked = true;
else
chk.checked = false;
If you want to do it in javascript
<checkbox Id="chk" class="chkbox"/>
JS:
if(yourcondition==true)
chk.checked = true;
else
chk.checked = false;
If you're using MVC and passing in model values correctly from your controller, then
@Html.CheckBoxFor(model => model.checkBox1)
...is all you need. The html-helper does the logic to figure out whether or not to insert the checked="checkbox"
code.
Otherwise, without the HTML-helper you can dynamically generate the attribute yourself (others have pointed out how), but don't make the mistake of thinking that checked = ""
will leave the box unchecked. See this answer for an explanation.
if(condition = true)
{
@Html.CheckBoxFor(x => x.Test, new { @checked = true })
}
else
{
@Html.CheckBoxFor(x => x.Test)
}
There is a simpler way to include or not include the checked
attribute if you are writing our your own <input>
instead of using alternatives such as Html.CheckBoxFor
:
<input type="checkbox" checked="@isChecked">
Razor is smart enough to automatically generate either
<input type="checkbox" checked="checked">
or
<input type="checkbox">
depending on whether isChecked
is true
or false
. No need for if statements or duplicate code.
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.