C# 通过隐藏字段发送复选框状态(已选中或未选中)
*.cshtml页面C# 通过隐藏字段发送复选框状态(已选中或未选中),c#,asp.net-mvc,C#,Asp.net Mvc,*.cshtml页面 @{ var companyLoginFormViewModel = TempData["CompanyLoginFormViewModel"] as CompanyLoginFormViewModel; } <form class="login-form" action="@Url.Action("Login")" name="companyLoginForm" method="post"> <
@{
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>
行动方法:
[HttpPost]
public virtual async Task<JsonResult> Login(LoginViewModel loginModel)
{
if (!ModelState.IsValid) //here it shows validation error
{
throw new UserFriendlyException(L("FormIsNotValidMessage"));
}
}
[HttpPost]
公共虚拟异步任务登录(LoginViewModel loginModel)
{
if(!ModelState.IsValid)//此处显示验证错误
{
抛出新的UserFriendlyException(L(“FormsNotValidMessage”);
}
}
问题:当我通过hiden字段传递true
或false
时,它总是说RememberMe字段是必需的。
服务器端的验证错误。但该属性不是必需的字段吗?你能告诉我为什么会这样吗?谢谢。您可以在隐藏字段中添加class=“ignore”
,并将其放入javascript代码中,以便在客户端忽略:
$.validator.setDefaults({
ignore: ".ignore"
});
服务器端:
@Html.Hiddenfor(model => model.rememberMe,
new Dictionary<string, object> { { "data-val", false }})
@Html.Hiddenfor(model=>model.rememberMe,
新字典{{“数据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>
}
@model companyLogiformViewModel
@{
}
@使用(Html.BeginForm(“您的操作”、“您的控制器”、FormMethod.Post))
{
@Html.Hiddenfor(model=>model.rememberMe,
新字典{{“数据val”,false})
@L(“登录”)
}
为什么不使用强类型帮助程序生成视图。为什么要使用ViewData
而不是将模型传递给视图(并且使用@model CompanyLoginFormViewModel
?bool
的类型是必填字段-它必须是true
或false
,并且不能是null
。唯一的解释是该值不是true或false。请检查生成的html(尽管这一切都可以通过正确生成视图来解决)为了测试,只需注释掉隐藏的input@StephenMuecke是的,它是这样生成的。
。平均值是null
?但是模型的上述属性是false
否。那么它是怎么发生的呢?谢谢。是的,它意味着它是null
-它应该是value=“True”
或value=“false”
否则。请停止手动生成html:)-您正在使用MVC-利用其功能。您应该添加自己的答案并接受它:)这与此无关。它只适用于客户端验证,OP甚至不使用任何客户端验证(默认情况下,隐藏字段将被忽略,因此即使OP是,也没有必要这样做。
@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>
}