转载自 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;

  1. public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable
  2. {
  3. public override bool IsValid(object value)
  4. {
  5. if (value is bool)
  6. return (bool)value;
  7. else
  8. return true;
  9. }
  10.  
  11. public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
  12. ModelMetadata metadata,
  13. ControllerContext context)
  14. {
  15. yield return new ModelClientValidationRule
  16. {
  17. ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
  18. ValidationType = "booleanrequired"
  19. };
  20. }
  21. }

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;

  1. [BooleanRequired(ErrorMessage = "You must accept the terms and conditions.")]
  2. [Display(Name = "I accept the terms and conditions")]
  3. public bool TermsAndConditionsAccepted { get; set; }

Next, create a simple view with a form that includes you boolean property;

  1. @model MyModel@using (Html.BeginForm())
  2. {
  3. <fieldset>
  4. <legend>Terms and Conditions</legend>
  5. @Html.ValidationSummary(true, "Please correct the errors and try again.")
  6. <p>
  7. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  8. Fusce facilisis ullamcorper consequat. Vestibulum non sapien lectus.
  9. Nullam at quam eu sapien mattis ultrices.
  10. </p>
  11. <ol>
  12. <li>
  13. @Html.CheckBoxFor(m => m.TermsAndConditionsAccepted)
  14. @Html.LabelFor(m => m.TermsAndConditionsAccepted, new { @class = "checkbox" })
  15. @Html.ValidationMessageFor(m => m.TermsAndConditionsAccepted)
  16. </li>
  17. </ol>
  18. <input type="submit" value="Submit" />
  19. </fieldset>
  20. }

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);

  1. <script type="text/javascript">
  2. (function ($) {
  3. $.validator.unobtrusive.adapters.addBool("booleanrequired", "required");
  4. } (jQuery));
  5. </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)的更多相关文章

  1. ASP.NET Core Web 应用程序系列(二)- 在ASP.NET Core中使用Autofac替换自带DI进行批量依赖注入(MVC当中应用)

    在上一章中主要和大家分享在MVC当中如何使用ASP.NET Core内置的DI进行批量依赖注入,本章将继续和大家分享在ASP.NET Core中如何使用Autofac替换自带DI进行批量依赖注入. P ...

  2. ASP.NET MVC中为DropDownListFor设置选中项的方法

    在MVC中,当涉及到强类型编辑页,如果有select元素,需要根据当前Model的某个属性值,让Select的某项选中.本篇只整理思路,不涉及完整代码. □ 思路 往前台视图传的类型是List< ...

  3. 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 ...

  4. MVC中发生System.Data.Entity.Validation.DbEntityValidationException验证异常的解决方法

    发生System.Data.Entity.Validation.DbEntityValidationException这个异常的时候,如果没有用特定的异常类去捕捉,是看不到具体信息的. 通常都是用Sy ...

  5. MVC 中@Html.DropDownListFor() 设置选中项 这么不好使 ? [问题点数:40分,结帖人lkf181]

    http://bbs.csdn.net/topics/390867060 由于不知道错误原因在哪 我尽量把代码都贴出来吧:重点是:在 Controller 类里 我给 SelectListItem集合 ...

  6. MVC中导航菜单,选中项的高亮问题。

      这个菜单是放在母板页的.比如当前选中的是异常业务监控.如果页面刷新了.就会变成第一张图..选择其他的选项也会,因为页面会刷新嘛.. 怎么处理这个问题了? 答案是记录当前页面的url. 有两种解决思 ...

  7. MVC中导航菜单,选中项的高亮问题。。

    先上图:             这个菜单是放在母板页的.比如当前选中的是异常业务监控.如果页面刷新了.就会变成第一张图..选择其他的选项也会,因为页面会刷新嘛.. 怎么处理这个问题了? 答案是记录当 ...

  8. 在ASP.NET MVC中使用Area区域

    在大型的ASP.NET mvc5项目中一般都有许多个功能模块,这些功能模块可以用Area(中文翻译为区域)把它们分离开来,比如:Admin,Customer,Bill.ASP.NET MVC项目中把各 ...

  9. ASP.NET MVC中的Session设置

    最近在ASP.NET MVC项目中碰到这样的情况:在一个controller中设置了Session,但在另一个controller的构造函数中无法获取该Session,会报"System.N ...

随机推荐

  1. (转载)ios关闭虚拟键盘的几种方法

    在iOS应用开发中,有三类视图对象会打开虚拟键盘,进行输入操作,但如何关闭虚拟键盘,却没有提供自动化的方法.这个需要我们自己去实现.这三类视图对象分别是UITextField,UITextView和U ...

  2. hihoCoder hiho一下 第四十八周 题目1 : 拓扑排序·二

    题意: 给定一个拓扑图,其中部分结点含有1个病毒,每个结点只要收到病毒就会立即往出边所能到达的点传播,病毒数可叠加,求所有结点的病毒数总和. 思路: 根据拓扑的特点,每个入度为0的点肯定不会再被传播病 ...

  3. ecshop 在首页每个商品下显示已销售数量

    1.在includes/lib_goods.php文件末尾加入以下代码 function get_buy_sum($goods_id) { $sql = "select sum(goods_ ...

  4. 利用android proguard混淆代码

    利用android proguard混淆代码 2014-02-05 17:50 1207人阅读 评论(1) 收藏 举报 网上虽然有很多相关博客,不过貌似都不是最新版的..于是百度+谷歌+github上 ...

  5. HttpWebRequest模拟c#网站登录

     用户名 密码 模拟登录asp.net开发的网站 关心两个问题:通过控件属性获取数据.响应事件. 上面是一个普通的asp.net表单.输入用户名.密码后,点击按钮将会进入各自绑定的后台函数,而不仅仅是 ...

  6. Oracle时间函数numtoyminterval()

    格式:NumToYMInterval(n, interval_unit); n: 数值类型 interval_unit: 'YEAR', 'MONTH' ,或其他可以转换成这两个值之一的表达式   N ...

  7. C#中实现对Excel特定文本的搜索

    打开Excel的VBA帮助,查看Excel的对象模型,很容易找到完成这个功能需要的几个集合和对象: Application.Workbooks. Workbook.Worksheets还有Worksh ...

  8. win下 golang 跨平台编译

    mac 下编译其他平台的执行文件方式请参看这篇文章,http://www.cnblogs.com/ghj1976/archive/2013/04/19/3030703.html  本篇文章是win下的 ...

  9. TortoiseSVN 插件配置及使用方法

    一.安装和配置 TortoiseSVN的下载地址 32bit:TortoiseSVN-1.8.2.24708-win32-svn-1.8.3.msi 64bit:TortoiseSVN-1.8.2.2 ...

  10. VS2010安装EntityFramework5.0

    EntityFramework 当前最新版本是6.0,2012年10月份发布,不过是alpha1版本,稳定版本是8月份发布的5.0版本,对于初学者来说,还是别在测试版上折腾了,先学习稳定的5.0版本, ...