ASP.NET MVC中的验证

来源:互联网 发布:平板软件强制搬家 编辑:程序博客网 时间:2024/05/16 08:24

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<MvcApplication4.Models.Customer>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Create
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    
<h2>Create</h2>

    
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again."%>

    
<% using (Html.BeginForm()) {%>

        
<fieldset>
            
<legend>Fields</legend>
            
<p>
                
<label for="NameStyle">NameStyle:</label>
                
<%= Html.TextBox("NameStyle"%>
                
<%= Html.ValidationMessage("NameStyle""*"%>
            
</p>
            
<p>
                
<label for="Title">Title:</label>
                
<%= Html.TextBox("Title"%>
                
<%= Html.ValidationMessage("Title""*"%>
            
</p>
            
<p>
                
<label for="FirstName">FirstName:</label>
                
<%= Html.TextBox("FirstName"%>
                
<%= Html.ValidationMessage("FirstName""*"%>
            
</p>
            
<p>
                
<label for="MiddleName">MiddleName:</label>
                
<%= Html.TextBox("MiddleName"%>
                
<%= Html.ValidationMessage("MiddleName""*"%>
            
</p>
            
<p>
                
<label for="LastName">LastName:</label>
                
<%= Html.TextBox("LastName"%>
                
<%= Html.ValidationMessage("LastName""*"%>
            
</p>
            
<p>
                
<label for="Suffix">Suffix:</label>
                
<%= Html.TextBox("Suffix"%>
                
<%= Html.ValidationMessage("Suffix""*"%>
            
</p>
            
<p>
                
<label for="CompanyName">CompanyName:</label>
                
<%= Html.TextBox("CompanyName"%>
                
<%= Html.ValidationMessage("CompanyName""CompanyName不能为空"%>
            
</p>
            
<p>
                
<label for="SalesPerson">SalesPerson:</label>
                
<%= Html.TextBox("SalesPerson"%>
                
<%= Html.ValidationMessage("SalesPerson""*"%>
            
</p>
            
<p>
                
<label for="EmailAddress">EmailAddress:</label>
                
<%= Html.TextBox("EmailAddress"%>
                
<%= Html.ValidationMessage("EmailAddress""EmailAddress不能为空"%>
            
</p>
            
<p>
                
<label for="Phone">Phone:</label>
                
<%= Html.TextBox("Phone"%>
                
<%= Html.ValidationMessage("Phone""*"%>
            
</p>
            
<p>
                
<label for="PasswordHash">PasswordHash:</label>
                
<%= Html.TextBox("PasswordHash"%>
                
<%= Html.ValidationMessage("PasswordHash""*"%>
            
</p>
            
<p>
                
<label for="PasswordSalt">PasswordSalt:</label>
                
<%= Html.TextBox("PasswordSalt"%>
                
<%= Html.ValidationMessage("PasswordSalt""*"%>
            
</p>
            
<p>
                
<label for="rowguid">rowguid:</label>
                
<%= Html.TextBox("rowguid"%>
                
<%= Html.ValidationMessage("rowguid""*"%>
            
</p>
            
<p>
                
<label for="ModifiedDate">ModifiedDate:</label>
                
<%= Html.TextBox("ModifiedDate"%>
                
<%= Html.ValidationMessage("ModifiedDate""*"%>
            
</p>
            
<p>
                
<input type="submit" value="Create" />
            
</p>
        
</fieldset>

    
<% } %>

    
<div>
        
<%=Html.ActionLink("Back to List""Index"%>
    
</div>

</asp:Content>

如果使用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
<string, string> _errors = new Dictionary<string, string>();
        
        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 { getset; }

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

        [Required]
        
public string Description { getset; }

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

    }
}