How do I set a checkbox in razor view?
You should set the AllowRating
property to true
, preferably in the controller or model.
Like other inputs, the checkbox's state reflects the value of the property.
The syntax in your last line is correct.
@Html.CheckBoxFor(x => x.Test, new { @checked = "checked" })
That should definitely work. It is the correct syntax. If you have an existing model and AllowRating is set to true then MVC will add the checked attribute automatically. If AllowRating is set to false MVC won't add the attribute however if desired you can using the above syntax.
This works for me:
<input id="AllowRating" type="checkbox" @(Model.AllowRating?"checked='checked'":"") style="" onchange="" />
If you really wants to use HTML Helpers:
@Html.CheckBoxFor(m => m.AllowRating, new { @checked = Model.AllowRating})
Also take into account that if m.AllowRating is false, it will fail to set to status checked in your examples.