[asp.net-mvc-3] How to set a CheckBox by default Checked in ASP.Net MVC

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,,,,

This question is related to asp.net-mvc-3

The answer is


Old question, but another "pure razor" answer would be:

@Html.CheckBoxFor(model => model.As, htmlAttributes: new { @checked = true} )

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();
}

@Html.CheckBox("yourId", true, new { value = Model.Ischecked })

This will certainly work


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>

You could set your property in the model's constructor

public YourModel()
{
    As = true;
}

My way is @Html.CheckBoxFor(model => model.As, new { @value= "true" }) (meaning is checked)