How to set a CheckBox by default Checked in ASP.Net MVC

asp.net Mvc-3

asp.net Mvc-3 Problem Overview


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

asp.net Mvc-3 Solutions


Solution 1 - asp.net Mvc-3

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.

Solution 2 - asp.net Mvc-3

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

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

Solution 3 - asp.net Mvc-3

You could set your property in the model's constructor

public YourModel()
{
    As = true;
}

Solution 4 - asp.net Mvc-3

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

This will certainly work

Solution 5 - asp.net Mvc-3

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>

Solution 6 - asp.net Mvc-3

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

Solution 7 - asp.net Mvc-3

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAvinash SinghView Question on Stackoverflow
Solution 1 - asp.net Mvc-3Darin DimitrovView Answer on Stackoverflow
Solution 2 - asp.net Mvc-3tonjoView Answer on Stackoverflow
Solution 3 - asp.net Mvc-3AnonymousView Answer on Stackoverflow
Solution 4 - asp.net Mvc-3Georges NicolasView Answer on Stackoverflow
Solution 5 - asp.net Mvc-3Clement HoangView Answer on Stackoverflow
Solution 6 - asp.net Mvc-3dunwanView Answer on Stackoverflow
Solution 7 - asp.net Mvc-3Dzu VuView Answer on Stackoverflow