mvc自带数据验证机制
写的一个简单的mvc自带数据验证机制
PeopleModels.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Web.Mvc; using System.Web.Security; namespace WebSql.Web.Models { /// <summary> /// 人,数据验证属性 /// </summary> public class PeopleModels { /* 数据验证,System.ComponentModel.DataAnnotations名称空间中的属性 */ [Required(ErrorMessage="名字不能空")] [StringLength(50,ErrorMessage="您输入的名字过长,不能超过50个字符")] [DisplayName("姓名")] public string Name { get; set; } [Required(ErrorMessage = "年龄不能空")] [Range(1,130,ErrorMessage="年龄输入超出范围")] [DisplayName("年龄")] public int Age { get; set; } [Required(ErrorMessage = "性别不能空")] [DisplayName("性别")] public string Sex { get; set; } [Required(ErrorMessage = "邮箱不能空")] [RegularExpression(@"^[\w\-\.]+@[\w\-\.]+(\.\w+)+$",ErrorMessage="邮箱输入有误")] [DisplayName("邮箱")] public string Email { get; set; } } }
Authentication/Index.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<WebSql.Web.Models.PeopleModels>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> 用户信息 </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>张三详细信息</h2> <% Html.BeginForm("Index","Authentication",FormMethod.Post); %> <%:Html.LabelFor(m=>m.Name) %>:<%:Html.TextBoxFor(m=>m.Name) %><%:Html.ValidationMessageFor(m=>m.Name)%><br/> <%:Html.LabelFor(m=>m.Sex) %>:<%:Html.TextBoxFor(m=>m.Sex) %><%:Html.ValidationMessageFor(m=>m.Sex) %><br/> <%:Html.LabelFor(m=>m.Age) %>:<%:Html.TextBoxFor(m=>m.Age) %><%:Html.ValidationMessageFor(m=>m.Age) %><br /> <%:Html.LabelFor(m=>m.Email) %>:<%:Html.TextBoxFor(m=>m.Email) %><%:Html.ValidationMessageFor(m=>m.Email) %><br /> <input type="submit" value="提交" /> <%Html.EndForm(); %> </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="JsContent" runat="server"> </asp:Content>
AuthenticationController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WebSql.Web.Models; namespace WebSql.Web.Controllers { /// <summary> /// 数据验证测试 /// </summary> public class AuthenticationController : Controller { public ActionResult Index() { return View(); } [HttpPost] [Authorize(Order = 1)] //form验证 public ActionResult Index(PeopleModels peopleModels) {
//数据验证
if (ModelState.IsValid) { ViewData["Menssage"] = "数据基本验证成功"; } return View(peopleModels); } } }