* .cshtml页面
@{
var companyLoginFormViewModel = TempData["CompanyLoginFormViewModel"] as CompanyLoginFormViewModel;
}
<form class="login-form" action="@Url.Action("Login")" name="companyLoginForm" method="post">
<input type="hidden" name="rememberMe" value="@companyLoginFormViewModel.LoginViewModel.RememberMe" />
<button type="submit" class="btn btn-success uppercase">@L("LogIn")</button>
</form>
注意:此值(@companyLoginFormViewModel.LoginViewModel.RememberMe
)始终为true
或false
虚拟机
public class CompanyLoginFormViewModel
{
public LoginViewModel LoginViewModel { get; set; }
}
public class LoginViewModel
{
public bool RememberMe { get; set; }
}
行动方法:
[HttpPost]
public virtual async Task<JsonResult> Login(LoginViewModel loginModel)
{
if (!ModelState.IsValid) //here it shows validation error
{
throw new UserFriendlyException(L("FormIsNotValidMessage"));
}
}
问题:当我通过hiden字段传递true
或false
时,它总是在服务器端显示The RememberMe field is required.
验证错误。但该属性是not a required
字段?你能告诉我为什么会这样吗?感谢。
答案 0 :(得分:0)
您可以在隐藏字段中添加class="ignore"
,并将其放在您的javascript代码中,以便在客户端忽略:
$.validator.setDefaults({
ignore: ".ignore"
});
服务器端:
@Html.Hiddenfor(model => model.rememberMe,
new Dictionary<string, object> { { "data-val", false }})
您正在使用MVC,请使用它的设施:
@model CompanyLoginFormViewModel
@{
}
@using (Html.BeginForm("Your Action","your controller",FormMethod.Post))
{
@Html.Hiddenfor(model => model.rememberMe,
new Dictionary<string, object> { { "data-val", false } })
<button type="submit" class="btn btn-success uppercase">@L("LogIn")</button>
}