【发布时间】:2013-05-08 07:55:35
【问题描述】:
我在我的 ASP.Net MVC 项目中使用 CheckBox,
我想设置checkBox默认勾选,
我的复选框是
@Html.CheckBoxFor(model => model.As, new { @checked = "checked" })
但它不起作用,,,,
【问题讨论】:
-
将模型属性设置为 true
标签: asp.net-mvc-3
我在我的 ASP.Net MVC 项目中使用 CheckBox,
我想设置checkBox默认勾选,
我的复选框是
@Html.CheckBoxFor(model => model.As, new { @checked = "checked" })
但它不起作用,,,,
【问题讨论】:
标签: asp.net-mvc-3
在渲染视图的控制器操作中,您可以将模型的 As 属性设置为 true:
model.As = true;
return View(model);
在你看来很简单:
@Html.CheckBoxFor(model => model.As);
现在由于模型的 As 属性设置为 true,CheckBoxFor 助手将生成一个选中的复选框。
【讨论】:
checked="checked" 属性在视图中手动生成复选框。
As 属性的值,正如我在回答中已经解释的那样,应该在控制器操作中设置。但是我再重复一次,如果您不想遵循这种推荐的方法,您应该手动硬编码您的复选框:<input type="checkbox" name="As" value="true" checked="checked" /><input type="hidden" name="As" value="false" />。
老问题,但另一个“纯粹的剃须刀”答案是:
@Html.CheckBoxFor(model => model.As, htmlAttributes: new { @checked = true} )
【讨论】:
bool ?)
你可以在模型的构造函数中设置你的属性
public YourModel()
{
As = true;
}
【讨论】:
@Html.CheckBox("yourId", true, new { value = Model.Ischecked })
这肯定行得通
【讨论】:
另一种解决方案是使用 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>
【讨论】:
我在 Controller 中使用具有相同变量名的 viewbag。例如,如果变量名为“IsActive”并且我希望它在“创建”表单上默认为 true,则在创建操作上我设置值 ViewBag.IsActive = true;
public ActionResult Create()
{
ViewBag.IsActive = true;
return View();
}
【讨论】:
我的方式是@Html.CheckBoxFor(model => model.As, new { @value= "true" })(意思是检查)
【讨论】: