在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 ...
随机推荐
- 读取Excel文件中的单元格的内容和颜色
怎样读取Excel文件中的单元格的内容和颜色 先创建一个Excel文件,在A1和A2中随意输入内容,设置A1的字体颜色为红色,A2的背景为黄色.需要 using Excel = Microsoft.O ...
- 【C#学习笔记】从粘贴板复制文本
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- Android Studio 学习 - 基本控件的使用;Intent初学
Android Studio学习第三天. 今天主要学习 1. RadioButton.CheckBox.RatingBar.SeekBar等基础控件的使用. 结合Delphi中相类似的控件,在这些基本 ...
- 【英语】Bingo口语笔记(11) - 表示“身体抱恙”
- 一天一个Java基础——通过异常处理错误
<Thinking in Java>上对这章的讲解不少,可见重要性,学习和总结一些主要的记录下来. 一.创建自定义异常 package Exception; class SimpleExc ...
- CURL: CURLE_COULDNT_CONNECT问题探究
摘自:: 存储系统研究: socket connect error 99(Cannot assign request address) 这是最近使用libcurl写http服务的压力测试的时候遇到的 ...
- BroadcastReceiver应用详解
今天我们来讲一下Android中BroadcastReceiver的相关知识. BroadcastReceiver也就是“广播接收者”的意思,顾名思义,它就是用来接收来自系统和应用中的广播. 在And ...
- poj 2409(polya定理模板)
题意:给你n种颜色和m个小球,问你有多少种不同的方案! 分析:作为模板.. 代码实现: #include <iostream> #include <cstdio> #inclu ...
- Optional优雅的使用null
在我们学习和使用Guava的Optional之前,我们需要来了解一下Java中null.因为,只有我们深入的了解了null的相关知识,我们才能更加深入体会领悟到Guava的Optional设计和使用上 ...
- jvm调优之四:生产环境参数实例及分析【生产环境实例增加中】
java application项目(非web项目) 改进前: -Xms128m-Xmx128m-XX:NewSize=64m-XX:PermSize=64m-XX:+UseConcMarkSweep ...