ASP.NET MVC数据标记验证
如果我發布的文章里有錯誤請各路高手給指出。
?? 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>
?
轉載于:https://www.cnblogs.com/changminglong/archive/2010/08/19/1803645.html
總結
以上是生活随笔為你收集整理的ASP.NET MVC数据标记验证的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java笔记(四)各类容器,set,ma
- 下一篇: 文章标题注释