转载自 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)的更多相关文章

  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. 51nod1257 背包问题 V3

    分数规划经典.开始精度1e-3/1e-4都不行,1e-5就A了 #include<cstdio> #include<cstring> #include<cctype> ...

  2. UVa 156 Ananagrams

    题意:给出一些单词,在这些单词里面找出不能通过字母重排得到的单词(判断的时候不用管大小写),然后按照字典序输出. 学习的紫书的map= = 将每一个单词标准化 先都转化为小写,再排序(即满足了题目中说 ...

  3. WEBUS2.0 In Action - 索引操作指南(2)

    上一篇:WEBUS2.0 In Action - 索引操作指南(1) | 下一篇:WEBUS2.0 In Action - 搜索操作指南(1) 3. 添加.删除.撤销删除和修改文档 在WEBUS中要将 ...

  4. Android隐藏虚拟按键,关闭开机动画、开机声音

    /*********************************************************************** * Android隐藏虚拟按键,关闭开机动画.开机声音 ...

  5. HDU 5316 Magician (线段树,单值修改,微变形)

    题意:给一个初始序列A[1,n],第j个数字代表精灵j的power值,有两种操作:(1)查询区间[L,R] (2)修改某个精灵的power值. 但,查询的是区间[L,R]中一个美丽子序列sub[l,r ...

  6. 【英语】Bingo口语笔记(33) - 面部器官系列

    to play by ear Play就是玩的意思.可是,play by ear的意思并不是“玩耳朵”.这个词汇的来源和音乐有关系.它原来指的是那些会弹钢琴或某种乐器,但是却不会看五线谱的人.每当他们 ...

  7. uimodalpresentationformsheet resize ios7

    CROHomeCRAAddController *temp =[[CROHomeCRAAddControlleralloc] init]; temp.modalTransitionStyle = UI ...

  8. 【转】如何调整CHM文件中的字体!非常有爱!

    原文网址:http://www.cnblogs.com/lijh_ray/archive/2011/01/25/1944668.html 如果html中字体大小是用像素px来定义,那么在IE中无法调整 ...

  9. 2016第20周四java基础概念

    简单的说JDK=JRE+Java编译器.调试器.工具类库等:JRE=JVM(类似于jre目录下的bin)+必要运行的类库(类似于jre目录下的lib) JVM:Java Virtual Mechina ...

  10. 【转】C# 委托的介绍(delegate、Action、Func、predicate)

    委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递.事件是一种特殊的委托. 1.委托的声明 (1). delegate delegate我们常用到的一种声明 Delegat ...