当我们利用Visual Studio生成实体类以后,难免会用到验证功能(例如,用户登录时验证用户名是否为空,并加以显示)。
Visual Studio实体类:实体类
如果直接去编辑Visual Studio生成的实体类话,当数据库更新字段后,再次更新实体类的话,会覆盖我们所添加的验证代码。
那么我们就要避免在Visual Studio生成的类中去进行代码的编写。这就需要用到扩展Models类了。
1、让我们创建一个AccountModels.cs文件.
生成AccountModels,cs文件
2、开始编写AccountModels.cs(模型)文件的代码,注意注释的描述,对你的学习很有帮助.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations;//所添加的自定义验证引用 using System.ComponentModel;//所添加的自定义验证引用 namespace MvcTest.Models { /// <summary> /// 指定元数据类 /// </summary> [MetadataType(typeof(MemberMetadata))] //类名与MvcTest.edmx的表名相同,partial为局部类型修饰词,用来和实体数据类进行整合 public partial class Member { public class MemberMetadata { [DisplayName("用户id")] public int Id { get; set; } [Required]//必须字符 [DisplayName("用户名")]//定义说明文字,调用方法:<%: Html.LabelFor(m => m.UserName) %> public string UserName { get; set; } [Required] [StringMinLength(6, 18, ErrorMessage = "密码大于6,小于18")]//自定义验证,下面有代码 [DataType(DataType.Password)] [DisplayName("密码")] public string PassWord { get; set; } [Required] [Email(ErrorMessage = "请输入正确的Email")]//自定义验证,下面有代码 [DisplayName("Email")] public string Email { get; set; } [Required] [DisplayName("创建时间")] public DateTime CreateTime { get; set; } [Required] [DisplayName("最后登录时间")] public DateTime LogonTime { get; set; } [Required] [DisplayName("安全问题")] public string Quesion { get; set; } [Required] [DisplayName("安全答案")] public string Answer { get; set; } } /// <summary> /// 定义StringMinLength类,继承ValidationAttribute验证基础类 /// </summary> public class StringMinLength : ValidationAttribute { private int _MinLength; private int _MaxLength; /// <summary> /// 定义方法,进行赋值 /// </summary> /// <param name="MinLength">最小值</param> /// <param name="MaxLength">最大值</param> public StringMinLength(int MinLength, int MaxLength) { _MinLength = MinLength; _MaxLength = MaxLength; } /// <summary> /// 重写IsValid方法 /// </summary> /// <param name="value">验证时所传入的值,不管StringMinLength()方法定义几个参数,重写时只这样写:IsValid(object value)</param> /// <returns>override重写修饰符</returns> public override bool IsValid(object value) { if (value.ToString().Length < _MinLength) { return false; } if (value.ToString().Length > _MaxLength) { return false; } return true; } } /// <summary> /// 定义EmailAttribute类,继承RegularExpressionAttribute正则表达式类,做验证使用,可重复调用 /// </summary> public class EmailAttribute : RegularExpressionAttribute { // base 关键字用于从派生类中访问基类的成员 public EmailAttribute() : base(@"^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]{2,4})$") { } } } }
3、编写View(视图)代码.View我们用的是强类型绑定,还需要调用三个js,因为View用了母版页.所以另贴代码.这三个JS是验证时必须调用的.
<head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> </title> <script type="text/javascript" src="../../Scripts/MicrosoftAjax.js"></script> <script type="text/javascript" src="../../Scripts/MicrosoftMvcAjax.js"></script> <script type="text/javascript" src="../../Scripts/MicrosoftMvcValidation.js"></script> </head>
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcTest.Models.Member>" %> <%--Inherits="System.Web.Mvc.ViewPage<MvcTest.Models.Member>" 强类型--%> <asp:Content ID="registerTitle" ContentPlaceHolderID="TitleContent" runat="server"> 注册 </asp:Content> <asp:Content ID="registerContent" ContentPlaceHolderID="MainContent" runat="server"> <h2> 创建新帐户</h2> <p> 使用以下表单创建新帐户。 </p> <%--启用验证方法,必须在第一个using (Html.BeginForm())上面,Html的<form>标签无效--%> <%Html.EnableClientValidation(); %> <%--生成form表单--%> <% using (Html.BeginForm()) { %> <div> <fieldset> <legend>帐户信息</legend> <div class="editor-label"> <%: Html.LabelFor(m => m.UserName) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(m => m.UserName) %> <%--验证失败时所显示的错误信息--%> <%: Html.ValidationMessageFor(m => m.UserName) %> </div> <div class="editor-label"> <%: Html.LabelFor(m => m.PassWord) %> </div> <div class="editor-field"> <%: Html.PasswordFor(m => m.PassWord)%> <%: Html.ValidationMessageFor(m => m.PassWord)%> </div> <div class="editor-label"> <%: Html.LabelFor(m => m.Email) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(m => m.Email) %> <%: Html.ValidationMessageFor(m => m.Email) %> </div> <div class="editor-label"> <%: Html.LabelFor(m => m.Quesion) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(m => m.Quesion)%> <%: Html.ValidationMessageFor(m => m.Quesion)%> </div> <div class="editor-label"> <%: Html.LabelFor(m => m.Answer) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(m => m.Answer)%> <%: Html.ValidationMessageFor(m => m.Answer)%> </div> <p> <input type="submit" value="注册" /> </p> </fieldset> </div> <% } %> </asp:Content>
4、编写Controllers(控制器)
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Security.Principal; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using MvcTest.Models;//需要using Models. namespace MvcTest.Controllers { [HandleError]//处理由操作方法引发的异常 public class AccountController : Controller { //new实体类 MvcTestEntities db = new MvcTestEntities(); #region 注册 public ActionResult Register() { return View(); } [HttpPost]//为了避免在表单未提交的时候访问此注册方法,需加[HttpPost],只有通过在本页面通过Post传输方式提交的表单才会访问此方法 public ActionResult Register(Models.Member member) { //做验证判断,如果通过则执行数据库写入代码 if (ModelState.IsValid) { db.AddToMember(new Models.Member { UserName = member.UserName, PassWord = member.PassWord, Email = member.Email, Quesion = member.Quesion, Answer = member.Answer, CreateTime = DateTime.Now, LogonTime = DateTime.Now }); db.SaveChanges(); //跳转页面.参数1:操作名称,参数2:路由参数 return RedirectToAction("Index", "Home"); } return View(); } #endregion } }
运行效果