I am using CheckBox in my ASP.Net MVC project,
i want to set checkBox by default checked,
My CheckBox is
@Html.CheckBoxFor(model => model.As, new { @checked = "checked" })
but its not working,,,,
I am using CheckBox in my ASP.Net MVC project,
i want to set checkBox by default checked,
My CheckBox is
@Html.CheckBoxFor(model => model.As, new { @checked = "checked" })
but its not working,,,,
In your controller action rendering the view you could set the As property of your model to true:
model.As = true;
return View(model);
and in your view simply:
@Html.CheckBoxFor(model => model.As);
Now since the As property of the model is set to true, the CheckBoxFor helper will generate a checked checkbox.
checked="checked" attribute.As property on your model which, as I already explained in my answer, should be set in your controller action. But I repeat once again, if you don't want to follow this recommended approach you should hardcode your checkbox manually: <input type="checkbox" name="As" value="true" checked="checked" /><input type="hidden" name="As" value="false" />.Old question, but another "pure razor" answer would be:
@Html.CheckBoxFor(model => model.As, htmlAttributes: new { @checked = true} )
bool ?)public bool As { get; set; } = true; but I pray you are not working with spaghetti code like I am...An alternative solution is using jQuery:
<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
PrepareCheckbox();
});
function PrepareCheckbox(){
document.getElementById("checkbox").checked = true;
}
</script>
I use viewbag with the same variable name in the Controller. E.g if the variable is called "IsActive" and I want this to default to true on the "Create" form, on the Create Action I set the value ViewBag.IsActive = true;
public ActionResult Create()
{
ViewBag.IsActive = true;
return View();
}