我正在使用带有 C# 的 ASP.NET MVC。
我在我的 View 中使用 CheckBoxFor 来获取 RememberMe 的 bool 值。
这是我在 View 中的复选框:
<%:Html.CheckBoxFor(model => model.RememberMe)%>
并在 .js 函数中获取它的值。
默认设置为true 但如果我取消选中该框,它仍然会向 .js 函数返回真值。
viewModel 值的函数:
function getViewModel() {
var viewModel = {
'UserName': $("#UserName").val(),
'Password': $("#Password").val(),
'RememberMe': $("#RememberMe").val()
};
return viewModel;
}
它使其他值正确,但即使我取消选中它,RememberMe 也是正确的
请给我一些建议。
最佳答案
复选框元素的值属性是固定的——这不是您要检查的内容。只有在提交表单时选中该框,此名称/值对才会通过 HTTP 发送。
因此,查看是否在您的函数中选中了复选框,并相应地设置 View 模型属性值:
function getViewModel() {
var viewModel = {
'UserName': $("#UserName").val(),
'Password': $("#Password").val(),
'RememberMe': $("#RememberMe").is(":checked") ? "true" : "false"
};
return viewModel;
}
或者您想要传递的任何值而不是“true”或“false”
关于javascript - CheckBoxFor 在 ASP.NET MVC 的 javascript 函数中返回以前的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17087953/