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. publicclassPriceAttribute:ValidationAttribute{
  2. publicdoubleMinPrice{get;set;}
  3. publicoverrideboolIsValid(objectvalue){
  4. if(value==null){
  5. returntrue;
  6. }
  7. varprice=(double)value;
  8. if(price<MinPrice){
  9. returnfalse;
  10. }
  11. doublecents=price-Math.Truncate(price);
  12. if(cents<0.99||cents>=0.995){
  13. returnfalse;
  14. }
  15. returntrue;
  16. }
  17. }

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

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

  1. publicclassProductViewModel{
  2. [Price(MinPrice=1.99)]
  3. publicdoublePrice{get;set;}
  4. [Required]
  5. publicstringTitle{get;set;}
  6. }

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

  1. <%@PageLanguage="C#"Inherits="ViewPage"%>
  2. <%using(Html.BeginForm()){%>
  3. <%=Html.TextBoxFor(m=>m.Title)%>
  4. <%=Html.ValidationMessageFor(m=>m.Title)%>
  5. <%=Html.TextBoxFor(m=>m.Price)%>
  6. <%=Html.ValidationMessageFor(m=>m.Price)%>
  7. <inputtype="submit"/>
  8. <%}%>

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

  1. [HandleError]
  2. publicclassHomeController:Controller{
  3. publicActionResultIndex(){
  4. returnView(newProductViewModel());
  5. }
  6. [HttpPost]
  7. publicActionResultIndex(ProductViewModelmodel){
  8. returnView(model);
  9. }
  10. }

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

详解ASP.NET MVC 2自定义验证(asp.net mvc验证码)  ASP.NET 2 第1张

转载请说明出处
知优网 » 详解ASP.NET MVC 2自定义验证(asp.net mvc验证码)

发表评论

您需要后才能发表评论