验证由复选框创建的输入隐藏字段

时间:2015-04-17 06:11:47

标签: asp.net-mvc-4

模型

[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }

查看

@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" })

创建额外的字段

<input data-val="true" data-val-required="The Remember me? field is required." id="RememberMe" name="RememberMe" type="checkbox" value="true">
<input name="RememberMe" type="hidden" value="false">

更改浏览器开发者工具的价值

<input name="RememberMe" type="hidden" value="\%74udhdy">

如果任何手动注入隐藏值,通过将其更改为除布尔值之外的其他内容true / false..keep页面上的按钮,操作结果返回视图

如果控制器想要返回视图(模型)......

黄屏死亡......

我们如何验证复选框控件创建的额外隐藏字段?

更新 - 操作方法

[HttpPost]
[AllowAnonymous]
//[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
    //Logic to verify user
    //incase of any issue append modelstate.addmodelerror()
     return View(model);
}

服务器错误

 Server Error in '/' Application.

String was not recognized as a valid Boolean.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.FormatException: String was not recognized as a valid Boolean.

Source Error: 


Line 29:             </li>
Line 30:             <li>
Line 31:                 @Html.CheckBoxFor(m => m.RememberMe)
Line 32:                 @Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" })
Line 33:             </li>

Source File: d:\Projects\MVCTestProject\MVCTestProject\Views\Account\Login.cshtml    Line: 31 

Stack Trace: 

1 个答案:

答案 0 :(得分:0)

由于您使用具有签名

的强类型@Html.CheckBoxFor()助手
public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper,Expression<Func<TModel, bool>> expression)

帮助程序只接受boolean值(truefalse),导致返回视图时出错。

因为这只会在用户篡改隐藏输入时(以及未选中复选框的情况下)发生,那么最好让异常发生,或者重定向到自定义错误页面,但是您对如何在没有错误的情况下返回视图感兴趣,您可以检查模型在控制器中是否有效并删除相关的错误消息

[HttpPost]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
  if (!ModelState.IsValid)
  {
    // This will be hit if the checkbox is unchecked and the value of
    // the RememberMe hidden input is not "true" or "false"
    if (ModelState.ContainsKey("RememberMe"))
    {
      ModelState["RememberMe"].Errors.Clear(); } // Remove the model state error
      model.RememberMe = false; // set default when returning the view
    }
  }
  ....
  return View(model);
}