ASP.NET MVC中的验证


1.简单验证

在ASP.Net MVC中,验证是在Controller层,而错误呈现是在View层,Controller层是通过ModelState属性进行验证的,ModelState的状态是通过AddModelError()方法进行 添加的。

而在View层,是通过Html的辅助方法进行呈现的,这两个辅助方法分别是

Html.ValidationMessage()
Html.ValidationSummary()


[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create([Bind(Exclude="CustomerId")] Customer customer)
        {
            if (customer.CompanyName.Length == 0)
            {
                ModelState.AddModelError("CompanyName", "CompanyName不能为空");
            }
            if (customer.EmailAddress.Length == 0)
            {
                ModelState.AddModelError("EmailAddress", "EmailAddress不能为空");
            }
            if (!ModelState.IsValid)
            {
                return View();
            }
            try
            {
                _entities.AddToCustomer(customer);
                _entities.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>


    Create




    

Create

<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %> <% using (Html.BeginForm()) {%>
Fields

<%= Html.TextBox("NameStyle") %> <%= Html.ValidationMessage("NameStyle", "*") %>

<%= Html.TextBox("Title") %> <%= Html.ValidationMessage("Title", "*") %>

<%= Html.TextBox("FirstName") %> <%= Html.ValidationMessage("FirstName", "*") %>

<%= Html.TextBox("MiddleName") %> <%= Html.ValidationMessage("MiddleName", "*") %>

<%= Html.TextBox("LastName") %> <%= Html.ValidationMessage("LastName", "*") %>

<%= Html.TextBox("Suffix") %> <%= Html.ValidationMessage("Suffix", "*") %>

<%= Html.TextBox("CompanyName") %> <%= Html.ValidationMessage("CompanyName", "CompanyName不能为空") %>

<%= Html.TextBox("SalesPerson") %> <%= Html.ValidationMessage("SalesPerson", "*") %>

<%= Html.TextBox("EmailAddress") %> <%= Html.ValidationMessage("EmailAddress", "EmailAddress不能为空") %>

<%= Html.TextBox("Phone") %> <%= Html.ValidationMessage("Phone", "*") %>

<%= Html.TextBox("PasswordHash") %> <%= Html.ValidationMessage("PasswordHash", "*") %>

<%= Html.TextBox("PasswordSalt") %> <%= Html.ValidationMessage("PasswordSalt", "*") %>

<%= Html.TextBox("rowguid") %> <%= Html.ValidationMessage("rowguid", "*") %>

<%= Html.TextBox("ModifiedDate") %> <%= Html.ValidationMessage("ModifiedDate", "*") %>

<% } %>
<%=Html.ActionLink("Back to List", "Index") %>

如果使用Entityframework生成的Model,数据库设计时为不为空,那么生成的Model层该字段的Nullable属性就为false,即使在Controller没有做简单验证,在View层也会做是否为空的判断的。

2.使用IDataErrorInfo Interface

IDataErrorInfo接口的定义比较简单:

public interface IDataErrorInfo { string this[string columnName] { get; } string Error { get; } }

使用IDataErrorInfo Interface的步骤如下:

针对Model,创建一个Partial类
添加OnChanging和OnChanged Partial方法
实现IDataErrorInfo接口


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;

namespace MvcApplication4.Models
{
    public partial class Customer:IDataErrorInfo
    {
        private Dictionary&lt;string, string&gt; _errors = new Dictionary&lt;string, string&gt;();

        partial void OnCompanyNameChanging(string value)
        {
            if (value.Trim().Length == 0)
            {
                _errors.Add("CompanyName", "CompanyName is required");
            }
        }

        public string Error
        {
            get
            {
                return string.Empty;
            }
        }

        public string this[string columnName]
        {
            get
            {
                if (_errors.ContainsKey(columnName))
                {
                    return _errors[columnName];
                }
                return string.Empty;
            }
        }
    }
}

3.使用Data Annotation Validators

下载Data Annotations Model Binder sample ,下载地址在http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471
添加对 Microsoft.Web.Mvc.DataAnnotations.dll和System.ComponentModel.DataAnnotations.dll 的引用
在Global.asax.cs中的Application_Start()方法中配置
使用Data Annotation Validator Attributes
System.ComponentModel.DataAnnotations命名空间下包括四个属性:
Range:范围验证
ReqularExpression:正则表达式验证
Required:必须验证
StringLength:字符串长度验证
Validation:这是所有验证属性的基类。

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace MvcApplication4.Models
{
    public class Test
    {
        public int Id { get; set; }

        [Required]
        [StringLength(10)]
        public string Name { get; set; }

        [Required]
        public string Description { get; set; }

        [DisplayName("Price")]
        [Required]
        [RegularExpression(@"^\$?\d+(\.(\d{2}))?$")]
        public decimal UnitPrice { get; set; }

    }
}

作者:深山老林
出处:http://wlb.cnblogs.com/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。


《“ASP.NET MVC中的验证”》 有 1 条评论

  1. … [Trackback]…

    […] Informations on that Topic: nishizhen.cn/2010/03/asp-net-mvc中的验证/ […]…

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

验证码 * Time limit is exhausted. Please reload CAPTCHA.