详解ASP.NET MVC 2自定义验证

原创
开发 后端
ASP.NET MVC 2内置支持在服务器上验证数据注释验证属性,本文介绍如何使用System.ComponentModel.DataAnnotations中的基础类构建自定义验证属性

【51CTO独家特稿】ASP.NET MVC 2内置支持在服务器上验证数据注释验证属性,本文介绍如何使用System.ComponentModel.DataAnnotations中的基础类构建自定义验证属性,关于ASP.NET MVC 2中数据注释是如何工作的,请参考Brad的博客(http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html)。

#T#

我会介绍如何连接到ASP.NET MVC 2的客户端验证扩展,以便你可以在客户端上运行JavaScript验证逻辑。

我将创建一个PriceAttribute来验证某个值是否大于指定的价格,并且这个价格必须以99分结束,因此$20.00是无效的值,$19.99是有效的。下面是这个属性的代码:

  1. public class PriceAttribute : ValidationAttribute {  
  2.   public double MinPrice { getset; }  
  3.       
  4.   public override bool IsValid(object value) {  
  5.     if (value == null) {  
  6.       return true;  
  7.     }  
  8.     var price = (double)value;  
  9.     if (price < MinPrice) {  
  10.       return false;  
  11.     }  
  12.     double cents = price - Math.Truncate(price);  
  13.     if(cents < 0.99 || cents >= 0.995) {  
  14.       return false;  
  15.     }  
  16.          
  17.     return true;  
  18.   }  

注意如果值为空,返回的值是true,这个属性不会验证字段是否需要。我会在RequiredAttribute中验证值是否需要。它允许我将属性放在可选的值上,当用户将这个字段留为空时显示一个错误。

我们可以创建一个视图模型,然后应用这个属性到模型上进行快速测试,下面是这个模型的代码:

  1. public class ProductViewModel {  
  2.   [Price(MinPrice = 1.99)]  
  3.   public double Price { getset; }  
  4.  
  5.   [Required]  
  6.   public string Title { getset; }  

我们再快速地创建一个视图(Index.aspx)显示和编辑窗体:

  1. <%@ Page Language="C#" Inherits="ViewPage" %> 
  2.  
  3. <% using (Html.BeginForm()) { %> 
  4.  
  5.   <%= Html.TextBoxFor(m => m.Title) %> 
  6.     <%= Html.ValidationMessageFor(m => m.Title) %> 
  7.   <%= Html.TextBoxFor(m => m.Price) %> 
  8.     <%= Html.ValidationMessageFor(m => m.Price) %> 
  9.       
  10.     <input type="submit" /> 
  11. <% } %> 

现在我们只需要一个有两个行为的控制器,一个编辑视图,另一个接收提交的ProductViewModel。

  1. [HandleError]  
  2. public class HomeController : Controller {  
  3.   public ActionResult Index() {  
  4.     return View(new ProductViewModel());  
  5.   }  
  6.  
  7.   [HttpPost]  
  8.   public ActionResult Index(ProductViewModel model) {  
  9.     return View(model);  
  10.   }  

我们还没有开启客户端验证,下面来看看当我们查看这个页面并提交一些值时会发生什么。

结果

责任编辑:彭凡 来源: 51CTO
相关推荐

2009-08-04 13:35:16

ASP.NET自定义样

2009-07-22 15:27:39

ASP.NET MVC自定义路由

2011-04-19 10:33:16

ASP.NET自定义控

2009-09-18 10:20:26

PRG数据验证

2010-04-30 09:32:49

ASP.NET MVC

2009-08-06 17:13:56

ASP.NET自定义控

2009-08-10 14:16:59

ASP.NET自定义控

2009-07-28 09:32:41

ASP.NET自定义控

2009-04-09 09:51:09

ASP.NETSQL Server 自定义分页

2009-07-31 10:23:09

ASP.NET源码DateTimePic

2009-08-12 14:38:05

ASP.NET Dat

2010-03-19 09:17:16

ASP.NET MVC

2010-02-03 09:50:58

ASP.NET MVC

2009-08-10 16:58:45

ASP.NET安装部署

2011-09-08 13:56:41

ASP.NET性能

2009-08-01 12:00:15

ASP.NET服务器自ASP.NET服务器ASP.NET

2009-08-05 17:58:53

自定义集合ASP.NET 2.0

2009-08-06 09:18:01

ASP.NET自定义控ASP.NET控件开发

2009-07-31 14:49:22

asp.net自定义错

2009-09-11 09:18:17

ASP.NET MVC
点赞
收藏

51CTO技术栈公众号