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 { 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; }
}
}
- ASP.NET MVC中的验证
- ASP.NET MVC中的验证
- ASP.NET MVC 2中的数据验证
- MVC学习笔记之Asp.Net MVC 中的验证问题
- ASP.NET MVC 2 中的模型验证和元数据
- Asp.net MVC中的全局权限验证方法及实现
- Asp.net MVC中的"??"
- ASP. net MVC 验证码
- asp.net MVc 数据验证
- ASP.net MVC 属性验证
- ASP.NET MVC 3.0验证
- ASP.NET MVC 验证方式
- asp.net Mvc验证码
- ASP.NET MVC 数据验证
- Asp.net mvc 服务器验证
- Asp.net Mvc 数据验证
- MVC学习笔记之:ASP.NET MVC的客户端验证-jQuery.validate验证结合Model验证中的实现
- ASP.NET MVC中的ActionResult
- C#导出Excel|导出数据到Excel模板文件里
- 使用SQL Server2005的几个错误解决方案 错误代号: 5123 18452 18470
- 循环屏幕
- 电脑上每个键的作用!!!
- VC++快捷键
- ASP.NET MVC中的验证
- 更改oracle10g的归档模式和归档路径
- 在VC6中使用c API方式连接MySQL数据库
- 手机的性能测试分析
- Some really good english(2)
- VirtualBox虚拟磁盘转换成xen可用的格式
- 今晚没去上自习
- Oracle物化视图
- Some really good english(1)