(二)学习MVC之实现用户注册功能
学习地址:http://www.cnblogs.com/mzwhj/archive/2012/10/22/2720089.html
本文和学习地址不一样的地方是我自己添加了一些简单的注释和理解。
1.添加用户模型类和用户组模型类:Model/User.cs和Model/UserGroup.cs
User.cs
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace RegisterExample.Models { /// <summary> /// 用户模型 /// </summary> public class User { [Key] public int UserId { get; set; } /// <summary> /// 用户组Id /// </summary> // [System.Web.Mvc.Remote("Exists", "User", ErrorMessage = "用户名已存在")] //Remote特性可以利用服务器端的毁掉函数执行客户端的验证逻辑。在特性中可以设置客户端代码要调用的控制器名称和操作名称,这里的控制器名称是“User”,操作名称是“Exists” [Display(Name = "用户组Id")] //Display特性可以为模型属性设置友好的“显示名称” [Required(ErrorMessage = "×")] //当Required 指定的属性为null或空是,它的特性将会引发一个验证错误。ErrorMessage可以自定义错误提示消息。 public int GroupId { get; set; } /// <summary> /// 用户名 /// </summary> [Display(Name = "用户名", Description = "4-20个字符。")] //上面提到Name是显示名称,Description是提示。 [Required(ErrorMessage = "×")] [StringLength(20, MinimumLength = 4, ErrorMessage = "×")] //StringLength验证特性,这里的20表示允许的最大长度值,MinimumLength=4表示设定字符串的最小长度是4.若不符合设定值范围,则返回ErrorMessage的自定义错误提示消息。 public string UserName { get; set; } /// <summary> /// 密码 /// </summary> [Display(Name = "密码")] [Required(ErrorMessage = "×")] [StringLength(512)] public string Password { get; set; } /// <summary> /// 性别【0-男;1-女;2-保密】 /// </summary> [Display(Name = "性别")] [Required(ErrorMessage = "×")] [Range(0, 2, ErrorMessage = "×")] //Range(中文意思是范围)特性用来指定数值类型值的最小值和最大值。 public byte Gender { get; set; } /// <summary> /// Email /// </summary> [Display(Name = "Email", Description = "请输入您常用的Email。")] [Required(ErrorMessage = "×")] [EmailAddress(ErrorMessage = "×")] public string Email { get; set; } /// <summary> /// 密保问题 /// </summary> [Display(Name = "密保问题", Description = "请正确填写,在您忘记密码时用户找回密码。4-20个字符。")] [Required(ErrorMessage = "×")] [StringLength(20, MinimumLength = 4, ErrorMessage = "×")] public string SecurityQuestion { get; set; } /// <summary> /// 密保答案 /// </summary> [Display(Name = "密保答案", Description = "请认真填写,忘记密码后回答正确才能找回密码。2-20个字符。")] [Required(ErrorMessage = "×")] [StringLength(20, MinimumLength = 2, ErrorMessage = "×")] public string SecurityAnswer { get; set; } /// <summary> /// QQ号码 /// </summary> [Display(Name = "QQ号码")] [RegularExpression("^[1-9][0-9]{4-13}$", ErrorMessage = "×")] [StringLength(12, MinimumLength = 6, ErrorMessage = "×")] public string QQ { get; set; } /// <summary> /// 电话号码 /// </summary> [Display(Name = "电话号码", Description = "常用的联系电话(手机或固话),固话格式为:区号-号码。")] [RegularExpression("^[0-9-]{11-13}$", ErrorMessage = "×")] public string Tel { get; set; } /// <summary> /// 联系地址 /// </summary> [Display(Name = "联系地址", Description = "常用地址,最多80个字符。")] [StringLength(80, ErrorMessage = "×")] public string Address { get; set; } /// <summary> /// 邮编 /// </summary> [Display(Name = "邮编")] [RegularExpression("^[0-9]{6}$", ErrorMessage = "×")] //RegularExpression意思是正则表达式,是一种检查字符串和内容的简洁有效方式。如果输入的信息不能喝正则表达式匹配,就会看到错误提示消息。 public string PostCode { get; set; } /// <summary> /// 注册时间 /// </summary> public DateTime? RegTime { get; set; } // DateTime 是值类型,.NET 值类型一经初始化,就有必须有值,不能赋 null。但是数据库中任意类型都可以有空null,所以,.net 2.0 引入了可空类型,建立在泛型的基础上,int? 是 C# 的特定语法,实际上是 Nullable<int> //int? num1; //int num2; //num1 = null;这是对的。 //num2 = null;这是错的。 /// <summary> /// 上次登录时间 /// </summary> public DateTime? LastLoginTime { get; set; } /// <summary> /// 用户组 /// </summary> public virtual UserGroup Group { get; set; } //表示一个用户对应于一个用户组 } }
UserGroup.cs
using System.ComponentModel.DataAnnotations; namespace RegisterExample.Models { /// <summary> /// 用户组 /// </summary> public class UserGroup { [Key] public int UserGroupId { get; set; } /// <summary> /// 用户组类型 /// </summary> [Display(Name = "类型")] [Required(ErrorMessage = "×")] public UserGroupType Type { get; set; } /// <summary> /// 用户组名称 /// </summary> [Display(Name = "名称", Description = "2-12个字符。")] [Required(ErrorMessage = "×")] [StringLength(12, MinimumLength = 2, ErrorMessage = "×")] public string Name { get; set; } /// <summary> /// 说明 /// </summary> [Display(Name = "说明", Description = "最多50个字符。")] [StringLength(50, ErrorMessage = "×")] public string Description { get; set; } } /// <summary> /// 用户组类型 /// </summary> public enum UserGroupType { Anonymous, Limited, Normal, Special } }
2.添加控制器Control/UserControl.cs,然后先放着不管它。
3.在项目新建Repository文件夹,新建类:Repository/RegisterContext.cs,用来实现EF的Context。
RegisterContext.cs
using RegisterExample.Models; using System.Data.Entity; namespace RegisterExample.Repository { public class RegisterContext : DbContext { public DbSet<User> Users { get; set; } public RegisterContext() : base("DefaultConnection") //数据库连接字符串名字 { Database.CreateIfNotExists(); } } }
4.新建类:Repository/RepositotyBase.cs,可以用来做UserRepository的基类,里面写Add,Update,Delete,Find几个虚函数,方便在继承类里面这几个函数的名称统一。
RepositotyBase.cs
namespace RegisterExample.Repository { //建一个类RepositoryBase,用来做***Repository的基类,里面写Add,Update,Delete,Find几个虚函数,方便在继承类里面这几个函数的名称统一。 public class RepositoryBase<TModel> { private RegisterContext dbContext; public RepositoryBase() { dbContext = new RegisterContext(); } /// <summary> /// 添加【继承类重写后才能正常使用】 /// </summary> public virtual bool Add(TModel TModel) { return false; } //在基类中,必须将允许重写的每个成员标记为virtual。假如一个public或protected成员没有包含virtual修饰符,就不允许子类重写该成员。virtual标志着方法或属性可在派生类中被替换(重写)。 /// <summary> /// 更新【继承类重写后才能正常使用】 /// </summary> public virtual bool Update(TModel TModel) { return false; } /// <summary> /// 删除【继承类重写后才能正常使用】 /// </summary> public virtual bool Delete(int Id) { return false; } /// <summary> /// 查找指定值【继承类重写后才能正常使用】 /// </summary> public virtual TModel Find(int Id) { return default(TModel); } ~RepositoryBase() //不知道为什么前面要加“~”。 { if (dbContext != null) { dbContext.Dispose(); } } } }
5.新建类:Repository/UserRepository.cs,重写Add和Update方法。
UserRepository.cs
using System.Linq; using RegisterExample.Models; namespace RegisterExample.Repository { public class UserRepository:RepositoryBase<User> { private RegisterContext dbContext; public UserRepository() { dbContext = new RegisterContext(); } /// <summary> /// 添加用户 /// </summary> /// <param name="user">用户信息</param> /// <returns></returns> //用override修饰的任何成员都自动成为虚成员,用override修饰的任何方法都自动成为虚方法。只能对基类的虚方法进行重写,所以重写的方法也是虚方法。 public override bool Add(User user) { if (user == null) return false; dbContext.Users.Add(user); if (dbContext.SaveChanges() > 0) return true; else return false; } /// <summary> /// 更新用户信息 /// </summary> /// <param name="user"></param> /// <returns></returns> public override bool Update(User user) { dbContext.Users.Attach(user); dbContext.Entry<User>(user).State = System.Data.EntityState.Modified; if (dbContext.SaveChanges() > 0) return true; else return false; } /// <summary> /// 检查用户是否存在 /// </summary> /// <param name="UserName"></param> /// <returns></returns> public bool Exists(string UserName) { if (dbContext.Users.Any(u => u.UserName.ToUpper() == UserName.ToUpper())) return true; else return false; } } }
6.在项目新建Extensions文件夹,添加类Extemporaneous/DisplayDescriptionExtensions.cs,在生成的代码中将命名空间改为System.Web.Mvc.Html,添加两个静态方法DisplayDescription和DisplayDescriptionFor。
DisplayDescriptionExtensions.cs
using System.Linq.Expressions; namespace System.Web.Mvc.Html { public static class DisplayDescriptionExtensions { /// <summary> /// 模型描述信息 /// </summary> /// <param name="htmlHelper"></param> /// <param name="name"></param> /// <returns></returns> public static MvcHtmlString DisplayDescription(this HtmlHelper htmlHelper, string name) { ModelMetadata _modelMetadata = ModelMetadata.FromStringExpression(name, htmlHelper.ViewData); return MvcHtmlString.Create(_modelMetadata.Description); } /// <summary> /// 模型描述信息 /// </summary> /// <typeparam name="TModel"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="htmlHelper"></param> /// <param name="expression"></param> /// <returns></returns> public static MvcHtmlString DisplayDescriptionFor<TModel, TResult>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TResult>> expression) { ModelMetadata _modelMetadata = ModelMetadata.FromLambdaExpression(expression,htmlHelper.ViewData); return MvcHtmlString.Create(_modelMetadata.Description); } } }
8.制作验证码,上一篇文章主要讲这个,这里不多说。
9.在Models里添加用户注册模型类UserRegister 继承自User,在类中new一下密码字段,并添加重复密码和验证码字段。
写在Model/Users.cs上
/// <summary> /// 用户注册模型 /// </summary> [NotMapped] public class UserRegister : User { /// <summary> /// 密码 /// </summary> [Display(Name = "密码", Description = "6-20个字符。")] [Required(ErrorMessage = "×")] [StringLength(20, MinimumLength = 6, ErrorMessage = "×")] [DataType(DataType.Password)] public new string Password { get; set; } /// <summary> /// 确认密码 /// </summary> [Display(Name = "确认密码", Description = "再次输入密码。")] [Compare("Password", ErrorMessage = "×")] //Compare特性用于确保模型对象的两个属性具有相同的值。 [DataType(DataType.Password)] public string ConfirmPassword { get; set; } /// <summary> /// 验证码 /// </summary> [Display(Name = "验证码", Description = "请输入图片中的验证码。")] [Required(ErrorMessage = "×")] [StringLength(6, MinimumLength = 6, ErrorMessage = "×")] public string VerificationCode { get; set; } /// <summary> /// 没加密的用户信息 /// </summary> /// <returns></returns> public User GetUser() { //Password = Common.Text.Sha256(this.Password) return new User { Address = this.Address, Email = this.Email, Gender = this.Gender, GroupId = this.GroupId, Password = this.Password, PostCode = this.PostCode, QQ = this.QQ, RegTime = this.RegTime, SecurityAnswer = this.SecurityAnswer, SecurityQuestion = this.SecurityQuestion, Tel = this.Tel, UserName = this.UserName }; }
9.控制器UserControl代码。
using System.Web.Mvc; using RegisterExample.Models; using RegisterExample.Repository; using System.Drawing; namespace RegisterExample.Controllers { public class UserController : Controller { private UserRepository userRsy; // // GET: /User/ public ActionResult Index() { return View(); } public ActionResult Register() { return View(); } [HttpPost] public ActionResult Register(UserRegister userReg) { if (Session["VerificationCode"] == null || Session["VerificationCode"].ToString() == "") { Error _e = new Error { Title = "验证码不存在", Details = "在用户注册时,服务器端的验证码为空,或向服务器提交的验证码为空", Cause = Server.UrlEncode("<li>你注册时在注册页面停留的时间过久页已经超时</li><li>您绕开客户端验证向服务器提交数据</li>"), Solution = Server.UrlEncode("返回<a href='" + Url.Action("Register", "User") + "'>注册</a>页面,刷新后重新注册") }; return RedirectToAction("Error", "Prompt", _e); } else if (Session["VerificationCode"].ToString() != userReg.VerificationCode.ToUpper()) { ModelState.AddModelError("VerificationCode", "×"); return View(); } userRsy = new UserRepository(); if (userRsy.Exists(userReg.UserName)) { ModelState.AddModelError("UserName", "用户名已存在"); return View(); } User _user = userReg.GetUser(); _user.RegTime = System.DateTime.Now; if (userRsy.Add(_user)) { Notice _n = new Notice { Title = "注册成功", Details = "您已经成功注册,用户为:" + _user.UserName + " ,请牢记您的密码!", DwellTime = 5, NavigationName = "登陆页面", NavigationUrl = Url.Action("Login", "User") }; return RedirectToAction("Notice", "Prompt", _n); } else { Error _e = new Error { Title = "注册失败", Details = "在用户注册时,发生了未知错误", Cause = "系统错误", Solution = Server.UrlEncode("<li>返回<a href='" + Url.Action("Register", "User") + "'>注册</a>页面,输入正确的信息后重新注册</li><li>联系网站管理员</li>") }; return RedirectToAction("Error", "Prompt", _e); } } /// <summary> /// 绘制验证码 /// </summary> /// <returns></returns> public ActionResult VerificationCode() { int _verificationLength = 6; //定义一个整数变量,作为验证码的长度。 int _width = 100, _height = 20;//验证码背景大小? SizeF _verificationTextSize;//存储有序浮点数对,通常为矩形的宽度和高度。 SizeF 结构的 Height 和 Width 的单位取决于用于绘制的 Graphics 对象的 PageUnit 和 PageScale 设置。 Bitmap _bitmap = new Bitmap(Server.MapPath("~/Content/Images/Texture.jpg"), true);//Bitmap类是封装 GDI+ 位图,此位图由图形图像及其特性的像素数据组成。 Bitmap 是用于处理由像素数据定义的图像的对象。 TextureBrush _brush = new TextureBrush(_bitmap);//TextureBrush 类的每个属性都是 Brush 对象,这种对象使用图像来填充形状的内部。 此类不能被继承。 //获取验证码 string _verificationText = Common.Text.VerificationText(_verificationLength);//得到随机产生包含6个由数字和字符组成的字符串 //存储验证码 Session["VerificationCode"] = _verificationText.ToUpper();//把字符转化成对应的大写字母,储存在Session对象的VerificationCode变量中 //Session 对象用于存储关于用户的信息,或者为一个用户的 session 更改设置。存储于 session 对象中的变量存有单一用户的信息,并且对于应用程序中的所有页面都是可用的。存储于 session 对象中的信息通常是 name、id 以及参数。服务器会为每个新的用户创建一个新的 Session,并在 session 到期时撤销掉这个 Session 对象。 Font _font = new Font("Arial", 14, FontStyle.Bold); Bitmap _image = new Bitmap(_width, _height); Graphics _g = Graphics.FromImage(_image);//从指定的 Image 创建新的 Graphics。 //清空背景色 _g.Clear(Color.White); //绘制验证码 _verificationTextSize = _g.MeasureString(_verificationText, _font);//测量用指定的 _font 绘制的指定字符串_verificationText。 _g.DrawString(_verificationText, _font, _brush, (_width - _verificationTextSize.Width) / 2, (_height - _verificationTextSize.Height) / 2); _image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//将该 Image 保存到指定的文件或流。 return null; } public ActionResult Login() { return View(); } } }
10.打开UserControl.cs,在public ActionResult Register()上点右键添加视图,选强类型视图,模型类选择UserRegister,新建好Register.cshtml视图
Register.cshtml代码
@model RegisterExample.Models.UserRegister @{ ViewBag.Title = "用户注册"; Layout = "~/Views/Shared/_Layout.cshtml"; } @using (Html.BeginForm()) { @Html.ValidationSummary(true) <div class="form"> <dl> <dt>用户注册</dt> <dd> <div class="label">@Html.LabelFor(model => model.UserName):</div> <div class="ctrl"> @Html.EditorFor(model => model.UserName) @Html.ValidationMessageFor(model => model.UserName) @Html.DisplayDescriptionFor(model => model.UserName) </div> </dd> <dd> <div class="label">@Html.LabelFor(model => model.Gender):</div> <div class="ctrl"> @Html.RadioButton("Gender", 0) 男 @Html.RadioButton("Gender", 1) 女 @Html.RadioButton("Gender", 2, true) 保密 @Html.ValidationMessageFor(model => model) @Html.DisplayDescriptionFor(model => model) </div> </dd> <dd> <div class="label">@Html.LabelFor(model => model.Password):</div> <div class="ctrl"> @Html.PasswordFor(model => model.Password) @Html.ValidationMessageFor(model => model.Password) @Html.DisplayDescriptionFor(model => model.Password) </div> </dd> <dd> <div class="label">@Html.LabelFor(model => model.ConfirmPassword):</div> <div class="ctrl"> @Html.PasswordFor(model => model.ConfirmPassword) @Html.ValidationMessageFor(model => model.ConfirmPassword) @Html.DisplayDescriptionFor(model => model.ConfirmPassword) </div> </dd> <dd> <div class="label">@Html.LabelFor(model => model.SecurityQuestion):</div> <div class="ctrl"> @Html.EditorFor(model => model.SecurityQuestion) @Html.ValidationMessageFor(model => model.SecurityQuestion) @Html.DisplayDescriptionFor(model => model.SecurityQuestion) </div> </dd> <dd> <div class="label">@Html.LabelFor(model => model.SecurityAnswer):</div> <div class="ctrl"> @Html.EditorFor(model => model.SecurityAnswer) @Html.ValidationMessageFor(model => model.SecurityAnswer) @Html.DisplayDescriptionFor(model => model.SecurityAnswer) </div> </dd> <dd> <div class="label">@Html.LabelFor(model => model.Email):</div> <div class="ctrl"> @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email) @Html.DisplayDescriptionFor(model => model.Email) </div> </dd> <dd> <div class="label">验证码:</div> <div class="ctrl"> @Html.TextBoxFor(model => model.VerificationCode) @Html.ValidationMessageFor(model => model.VerificationCode) <img id="verificationcode" alt="" src="@Url.Action("VerificationCode", "User")" /> <a id="trydifferent" style="cursor:pointer">换一张</a> </div> </dd> <dd> <div class="label">注册条款:</div> <div class="ctrl"> @Html.CheckBox("Agreement", new { @class = "required" }) 我已阅读并同意注册条款 </div> </dd> <dd> <div class="label"></div> <div class="ctrl"> <input type="submit" value="注册" /> </div> </dd> </dl> <div class="clear"></div> </div> } <script type="text/javascript"> $("#trydifferent").click(function () { //alert(1); $("#verificationcode").attr("src", "/User/VerificationCode?" + new Date()); }) </script>
11.下面开始写注册处理的代码。在Controllers,在public ActionResult Register(){return View();}下面添加一个[HttpPost]方式的Register() Action。
已在前面的UserControl写好
12.新建提示类:Model/Prompts.cs
namespace RegisterExample.Models { /// <summary> /// 提醒注意 /// </summary> public class Notice { /// <summary> /// 标题 /// </summary> public string Title { get; set; } /// <summary> /// 详细内容 /// </summary> public string Details { get; set; } /// <summary> /// 停留时间【-1-不启用】 /// </summary> public int DwellTime { get; set; } /// <summary> /// 导航名称 /// </summary> public string NavigationName { get; set; } /// <summary> /// 导航地址 /// </summary> public string NavigationUrl { get; set; } } /// <summary> /// 错误 /// </summary> public class Error { /// <summary> /// 名称 /// </summary> public string Title { get; set; } /// <summary> /// 详细 /// </summary> public string Details { get; set; } /// <summary> /// 原因 /// </summary> public string Cause { get; set; } /// <summary> /// 解决方法 /// </summary> public string Solution { get; set; } } }
13.新建控制器:PromptControl,创建一个Notice方法,还有相对应的Prompt文件夹和Notice.cshtml视图
Notice.cshtml
@model RegisterExample.Models.Notice @{ ViewBag.Title = Model.Title; Layout = "~/Views/Shared/_Layout.cshtml"; } <div> <dl> <dt>@Html.DisplayFor(model => model.Title)</dt> <dd>@Html.DisplayFor(model => model.Details)</dd> @if (Model.DwellTime >= 0) { <dd>系统将在 <span id="time">@Model.DwellTime </span>秒后跳转登陆页面。如未自动跳转请点击<a href="@Model.NavigationUrl">@Model.NavigationName</a>。</dd> <script type="text/javascript"> function Jump(time) { //alert(1); window.setTimeout(function () { time--; $("#time").text(time); if (time > 0) Jump(time); else location.href = "@Model.NavigationUrl"; }, 1000); } Jump(@Model.DwellTime); </script> } </dl> </div>
14.创建本地连接的数据库,在Web.config中添加数据库信息:
<connectionStrings> <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=RegisterExample;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\RegisterExample.mdf" providerName="System.Data.SqlClient" /> </connectionStrings>
15.已经在UserControl创建一个Login方法,现还要有与之对应的视图:User/Login.cshtml
@{ ViewBag.Title = "用户登录"; Layout = "~/Views/Shared/_Layout.cshtml"; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Login</title> </head> <body> <div> <h2>欢迎来到登录页面</h2> </div> </body> </html>
16.运行成功,结束。