在ASP.NET MVC中验证checkbox 必须选中 (Validation of required checkbox in Asp.Net MVC)
转载自 http://blog.degree.no/2012/03/validation-of-required-checkbox-in-asp-net-mvc/
Why would you want to have a required checkbox, i.e. a checkbox that user would have to check? Well, a typical example would be that you have some sort of terms associated with submitting a form that the user has to agree to.
You might think that decorating a boolean property on one of your MVC models with a RequiredAttribute, would mean that if you presented that property in your view as a checkbox, that would require the user to click that checkbox before submitting the form. This is not the case however. If you take a look at the implementation of the RequiredAttribute it is actually casting the value to validate into a string and checking the string length. If it can’t cast the value to a string, it will just return true for IsValid.
It is quite easy however to create your own custom validation attribute that you could decorate your boolean property with. The following code checks if the decorated property is a bool, and if so, requires it to have been set to true;
public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
if (value is bool)
return (bool)value;
else
return true;
} public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
ModelMetadata metadata,
ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "booleanrequired"
};
}
}
Notice the GetClientValidationRules-method above where we specify the error message to display if client-side validation fails, and what the validation type is. The value we provide as the validation type will be rendered as the name of the rule in the HTML element, and will be used further down to tell jQuery how to validate this property.
After creating the new validation attribute, we need to apply it to a boolean property on out model;
[BooleanRequired(ErrorMessage = "You must accept the terms and conditions.")]
[Display(Name = "I accept the terms and conditions")]
public bool TermsAndConditionsAccepted { get; set; }
Next, create a simple view with a form that includes you boolean property;
@model MyModel@using (Html.BeginForm())
{
<fieldset>
<legend>Terms and Conditions</legend>
@Html.ValidationSummary(true, "Please correct the errors and try again.")
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Fusce facilisis ullamcorper consequat. Vestibulum non sapien lectus.
Nullam at quam eu sapien mattis ultrices.
</p>
<ol>
<li>
@Html.CheckBoxFor(m => m.TermsAndConditionsAccepted)
@Html.LabelFor(m => m.TermsAndConditionsAccepted, new { @class = "checkbox" })
@Html.ValidationMessageFor(m => m.TermsAndConditionsAccepted)
</li>
</ol>
<input type="submit" value="Submit" />
</fieldset>
}
Lastly, in order for client-side validation to work, you need to include the following script in your view (or you can just put line 3 in a javascript file that you reference);
<script type="text/javascript">
(function ($) {
$.validator.unobtrusive.adapters.addBool("booleanrequired", "required");
} (jQuery));
</script>
This just registers a new validation adapter for the boolean required attribute, where the first parameter is the adapter name and the second parameter is the name of jQuery validate rule. The adapter name should match the value we specified earlier as the validation type, and the jQuery validation required-rule will require the user to check the checkbox.
That’s it! This will make sure that the checkbox is checked by the user client-side (using jQuery unobtrusive validation*) and that the boolean property is set to true server-side when the form is submitted to the server.
*The ClientValidationEnabled and UnobtrusiveJavaScriptEnabled application settings must be set to true in your web.config for client-side validation to work.
在ASP.NET MVC中验证checkbox 必须选中 (Validation of required checkbox in Asp.Net MVC)的更多相关文章
- ASP.NET Core Web 应用程序系列(二)- 在ASP.NET Core中使用Autofac替换自带DI进行批量依赖注入(MVC当中应用)
在上一章中主要和大家分享在MVC当中如何使用ASP.NET Core内置的DI进行批量依赖注入,本章将继续和大家分享在ASP.NET Core中如何使用Autofac替换自带DI进行批量依赖注入. P ...
- ASP.NET MVC中为DropDownListFor设置选中项的方法
在MVC中,当涉及到强类型编辑页,如果有select元素,需要根据当前Model的某个属性值,让Select的某项选中.本篇只整理思路,不涉及完整代码. □ 思路 往前台视图传的类型是List< ...
- ASP.NET Core 中文文档 第二章 指南(4.1)ASP.NET Core MVC 与 Visual Studio 入门
原文:Getting started with ASP.NET Core MVC and Visual Studio 作者:Rick Anderson 翻译:娄宇(Lyrics) 校对:刘怡(Alex ...
- MVC中发生System.Data.Entity.Validation.DbEntityValidationException验证异常的解决方法
发生System.Data.Entity.Validation.DbEntityValidationException这个异常的时候,如果没有用特定的异常类去捕捉,是看不到具体信息的. 通常都是用Sy ...
- MVC 中@Html.DropDownListFor() 设置选中项 这么不好使 ? [问题点数:40分,结帖人lkf181]
http://bbs.csdn.net/topics/390867060 由于不知道错误原因在哪 我尽量把代码都贴出来吧:重点是:在 Controller 类里 我给 SelectListItem集合 ...
- MVC中导航菜单,选中项的高亮问题。
这个菜单是放在母板页的.比如当前选中的是异常业务监控.如果页面刷新了.就会变成第一张图..选择其他的选项也会,因为页面会刷新嘛.. 怎么处理这个问题了? 答案是记录当前页面的url. 有两种解决思 ...
- MVC中导航菜单,选中项的高亮问题。。
先上图: 这个菜单是放在母板页的.比如当前选中的是异常业务监控.如果页面刷新了.就会变成第一张图..选择其他的选项也会,因为页面会刷新嘛.. 怎么处理这个问题了? 答案是记录当 ...
- 在ASP.NET MVC中使用Area区域
在大型的ASP.NET mvc5项目中一般都有许多个功能模块,这些功能模块可以用Area(中文翻译为区域)把它们分离开来,比如:Admin,Customer,Bill.ASP.NET MVC项目中把各 ...
- ASP.NET MVC中的Session设置
最近在ASP.NET MVC项目中碰到这样的情况:在一个controller中设置了Session,但在另一个controller的构造函数中无法获取该Session,会报"System.N ...
随机推荐
- windows下github pages + hexo next 搭建个人博客
一.github pages 搭建个人博客一般需要购买域名和空间,github pages为我们提供了这两样东西,而且是免费的,相关介绍和使用方法参考这里 github pages. 二.Hexo 一 ...
- WEBUS2.0 In Action - [源代码] - C#代码搜索器
最近由于工作的需要, 要分析大量C#代码, 在数万个cs文件中搜索特定关键词. 这是一项非常耗时的工作, 用Notepad++要运行接近半个小时. 于是我利用WEBUS2.0 SDK创建了一个代码搜索 ...
- Js内置对象的应用
Boolean.Number.Objectfunction对象 另一种写法: var add=new Function("x","y",&q ...
- 【英语】Bingo口语笔记(77) - 临时改变计划的表达
- UITabbar item 设置笔记
很长一段时间都是用代码来写UITabbarController,试着用xib来写一次,但是遇到tabbar item的图标自定义的时候不知道从何入手,比如定义选定前和选定后的icon图片,这地方还是不 ...
- 《Write Optimized B-Trees》读书报告
论文原作者:Goetz Graefe, Microsoft.我读完这篇论文后颇有收获,所以写了一篇论文报告,旨在更精炼准确地阐述论文核心思想. 摘要:论文提出了一种方法,这种方法可以优化B树索引写性能 ...
- FPGA代码设计规范整理
1.设计中的FIFO.状态机接口需要有异常恢复状态和状态上报机制,格雷码电路防止被综合电路优化掉. a)自行设计的格雷码FIFO(一般用于连续数据流跨时钟域)用Synplify综合时,为了防止被优化需 ...
- nodejs 改变全局前缀
npm的包安装分为本地安装(local).全局安装(global)两种,从敲的命令行来看,差别只是有没有-g而已,比如: 复制代码 代码如下: npm install grunt # 本地安装npm ...
- 基于CentOS与VmwareStation10搭建Oracle11G RAC 64集群环境:2.搭建环境-2.4. 安装JDK
2.4.安装JDK 2.4.1.准备JDK 在百度搜索:JDK下载 2.4.2.上传JDK put E:\软件安装文件\jdk-8u11-linux-x64.rpm /home/linuxrac1/D ...
- 支持多种浏览器的纯css下拉菜单
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...