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

為{幸葍}努か 提交于 2019-11-26 22:37:30

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.

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

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

You could set your property in the model's constructor

public YourModel()
{
    As = true;
}
@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>

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();
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!