日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

ASP.NET MVC数据标记验证

發(fā)布時間:2025/3/15 asp.net 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ASP.NET MVC数据标记验证 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

如果我發(fā)布的文章里有錯誤請各路高手給指出。

?? DataAnnotation提供了一個簡單的方式,在應用中的Model和View 類中添加驗證規(guī)則,在ASP.NET MVC中有自動的綁定和UI輔助方法驗證支持。首先創(chuàng)建一個實體類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>

?

轉(zhuǎn)載于:https://www.cnblogs.com/changminglong/archive/2010/08/19/1803645.html

總結(jié)

以上是生活随笔為你收集整理的ASP.NET MVC数据标记验证的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。