默认情况下如何设置CheckBox在ASP.Net MVC中检查

时间:2013-05-08 07:55:36

标签: asp.net-mvc-3

我在ASP.Net MVC项目中使用CheckBox,

我想默认设置checkBox,

我的CheckBox是

@Html.CheckBoxFor(model => model.As, new { @checked = "checked" })

但它不起作用,,,,

7 个答案:

答案 0 :(得分:69)

在渲染视图的控制器操作中,您可以将模型的As属性设置为true:

model.As = true;
return View(model);

在您看来简单:

@Html.CheckBoxFor(model => model.As);

现在,由于模型的As属性设置为true,CheckBoxFor帮助器将生成一个选中的复选框。

答案 1 :(得分:35)

老问题,但另一个"纯剃刀"答案是:

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

答案 2 :(得分:2)

您可以在模型的构造函数中设置属性

public YourModel()
{
    As = true;
}

答案 3 :(得分:2)

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

这肯定会起作用

答案 4 :(得分:0)

另一种解决方案是使用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>

答案 5 :(得分:0)

我在Controller中使用具有相同变量名的viewbag。例如,如果变量被称为“IsActive”并且我希望在“创建”表单上默认为true,则在创建操作上我设置值ViewBag.IsActive = true;

public ActionResult Create()
{
    ViewBag.IsActive = true;
    return View();
}

答案 6 :(得分:0)

我的方式是@Html.CheckBoxFor(model => model.As, new { @value= "true" })(含义已选中)

相关问题