如果我发布的文章里有错误请各路高手给指出。
DataAnnotation提供了一个简单的方式,在应用中的Model和View 类中添加验证规则,在ASP.NET MVC中有自动的绑定和UI辅助方法验证支持。首先创建一个实体类Persons,代码如下
Models
namespace Mvc2Demo.Models
{
public class Person
{
[Required(ErrorMessage="用户名不能为空!")]
public String Name { get; set; }
[Range(0,150,ErrorMessage="年龄必须在0-150之间!")]
[Required(ErrorMessage="年龄不能为空!")]
public Int32 Age { get; set; }
[Required(ErrorMessage="邮箱地址不能为空!")]
[RegularExpression("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*",ErrorMessage="邮箱格式不正确,请重新填写!")]
public String Email { get; set; }
}
}
使用Required 、RegularExpression 等属性需要引用命名空间
using System.ComponentModel.DataAnnotations;
PersonController
namespace Mvc2Demo.Controllers
{
public class PersonController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Create()
{
Persons person= new Persons();
return View(person);
}
[HttpPost]
public ActionResult Create(Person person)
{
if (!ModelState.IsValid)
{
return View(person);
}
return View("Success");
}
}
}
View
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Mvc2Demo.Models.Person>" %>
2
3 <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
4 Create
5 </asp:Content>
6
7 <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
8 <h2>Create </h2>
9 <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
10 <% using (Html.BeginForm()) {%>
11 <fieldset>
12 <legend>Fields</legend>
13 <p>
14 <label for="Name">Name:</label>
15 <%= Html.TextBox("Name") %>
16 <%= Html.ValidationMessage("Name", "*") %>
17 </p>
18 <p>
19 <label for="Age">Age:</label>
20 <%= Html.TextBox("Age") %>
21 <%= Html.ValidationMessage("Age", "*") %>
22 </p>
23 <p>
24 <label for="Email">Email:</label>
25 <%= Html.TextBox("Email") %>
26 <%= Html.ValidationMessage("Email", "*") %>
27 </p>
28 <p>
29 <input type="submit" value="Create" />
30 </p>
31 </fieldset>
32
33 <% } %>
34 <div>
35 <%=Html.ActionLink("Back to List", "Index") %>
36 </div>
37 </asp:Content>