我已经在网上查看并应用了很多解决方法,即 Check/Uncheck checkbox with javascript? 但我的问题是在页面加载后检查复选框。我使用 $(window).load(function () 和 $(document).ready(function () 但它们都不起作用。但是,如果我可以设置选中复选框的 html 中的属性问题将得到解决。但是我无法通过 Javascript 变量设置此属性。我也尝试过使用 jQuery,但问题与渲染复选框后设置此属性有关。有解决问题的想法吗?
<input type="checkbox" class="form-check-input" id="chkAll" >
//Although the checkboz is already rendered at this stage I cannot set it
$(window).load(function () {
if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
document.getElementById("chkAll").checked = true;
}
});
和
//As the checkbox is not rendering during page load this method is useless
$(document).ready(function () {
if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
document.getElementById("chkAll").checked = true;
}
});
最佳答案
您不需要任何 JavaScript。您使用 CheckBox()
方法,该方法将根据您绑定(bind)到的 boolean
属性的值正确设置 checked
属性。问题是你对你的属性(property)没有约束力。将 View 中的代码更改为
@Html.CheckBox("IsAll")
如果ViewBag.IsAll的值为
true`则会被检查,否则不会。
关于javascript - 如何在渲染过程中选中复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43112657/