学用MVC4做网站一:用户
用户部分要实现的功能有:
一、用户
要实现这些目的首先新建用户(Model)模型
/// <summary> /// 用户模型 /// </summary> public class User { [Key] public int UserId { get; set; } /// <summary> /// 用户组Id /// </summary> [Display(Name="用户组Id")] [Required(ErrorMessage = "×")] public int GroupId { get; set; } /// <summary> /// 用户名 /// </summary> [Display(Name="用户名",Description="4-20个字符。")] [Required(ErrorMessage = "×")] [StringLength(20, MinimumLength = 4, ErrorMessage = "×")] public string UserName { get; set; } /// <summary> /// 密码 /// </summary> [Required] [StringLength(256)] public string Password { get; set; } /// <summary> /// 性别【0-男;1-女;2-保密】 /// </summary> [Display(Name="性别")] [Required(ErrorMessage = "×")] [Range(0,2,ErrorMessage = "×")] 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 = "×")] public string PostCode { get; set; } /// <summary> /// 注册时间 /// </summary> public DateTime? RegTime { get; set; } /// <summary> /// 上次登录时间 /// </summary> public DateTime? LastLoginTime { get; set; } /// <summary> /// 用户组 /// </summary> public virtual UserGroup Group { get; set; } }
下面添加用户Controller。在Controller文件夹点右键 选择新建控制器名称输入UserController,完成后生成代码如下:
using System.Web.Mvc; using CMS.Models; namespace CMS.Controllers { public class UserController : Controller { public ActionResult Register() { return View(); } // // POST: /User/Create [HttpPost] public ActionResult Register(UserRegister uerReg) { try { // TODO: Add insert logic here return RedirectToAction("Index"); } catch { return View(); } } } }
马上涉及的问题就是数据的存取,本来准备用Repository模式做,后来觉得用Repository模式在一个人写个简单那网站的情况下意义不大,写起来反而有点啰嗦,干脆用伪Repository模式写。项目中新建Repository文件夹。在文件夹中新建类CMS,用来实现EF的Context。代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using CMS.Models; namespace CMS.Repository { public class CMSContext:DbContext { public DbSet<User> Users { get; set; } } }
简单吧。再建一个类RepositoryBase,用来做***Repository的基类,里面写Add,Update,Delete,Find几个虚函数,方便在继承类里面这几个函数的名称统一。
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CMS.Repository { public class RepositoryBase<TModel> { private CMSContext dbContext; public RepositoryBase() { dbContext = new CMSContext(); } /// <summary> /// 添加【继承类重写后才能正常使用】 /// </summary> public virtual bool Add(TModel Tmodel) { return false; } /// <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(); } } } }
可以写UserRepository的具体实现了,新建UserRepository类。重写Add,Update方法后代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using CMS.Models; namespace CMS.Repository { public class UserRepository:RepositoryBase<User> { private CMSContext dbContext; public UserRepository() { dbContext = new CMSContext(); } /// <summary> /// 添加用户 /// </summary> /// <param name="user">用户信息</param> /// <returns></returns> 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) { var _user = dbContext.Users.SingleOrDefault(u => u.UserId == user.UserId); if (_user == null) return false; _user = user; if (dbContext.SaveChanges() > 0) return true; else return false; } //public override } }
到这里Repository的基本模式也出来了,现在MVC中的M和C都出来了就差V了,少了V相当于高富帅少了“富”在高,再帅都没用。那么马上下手为了写view做准备。
@Html.Label可以用来显示字段的Display(Name=“”),@Html.DisplayText显示模型中字段值。没有找到用来显示模型中字段的Display(……,Description=“”)属性的HtmlHelper。先自己写一个用。在项目中新建Extensions文件夹,右键添加类DisplayDescriptionExtensions,在生成的代码中将命名空间改为System.Web.Mvc.Html,添加两个静态方法DisplayDescription和DisplayDescriptionFor。完成后代码
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); } } }
好了,在视图中就可以直接用@Html.DisplayDescriptionFor(model => model.UserName)或@Html.DisplayDescription(“.UserName”)调用描述信息了.
到了这里后,大致的准备工作差不多了,还有两个小东东实现一下就可以写具体功能了。
第一个小东东:验证码。验证码分两块一是随机获取一定位数的字符,另一块是把字符绘制成图片。
在项目中添加Common 文件夹,在文件夹中新建Text类,在类实现函数VerificationText()利用Random获取指定长度的随机字符串,写完后的代码:
using System; namespace CMS.Common { /// <summary> /// 文本相关 /// </summary> public class Text { /// <summary> /// 获取验证码【字符串】 /// </summary> /// <param name="Length">验证码长度【必须大于0】</param> /// <returns></returns> public static string VerificationText(int Length) { char[] _verification = new Char[Length]; Random _random = new Random(); char[] _dictionary = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; for (int i = 0; i < Length; i++) { _verification[i] = _dictionary[_random.Next(_dictionary.Length - 1)]; } return new string(_verification); } } }
现在可以绘制验证码了,这里会用到.net的GDI+,我看了很多朋友写的验证码,一般都绘制了很多干扰点和干扰线,目的是为了使验证码不容易被电脑,个人觉得把绘制字的时候用材质刷绘制应该也能达到目的,所以找了一幅水彩画的材质。
用这个做字的材质也应该不太容易别识别吧,开始写绘图的代码,在UserController里新建名为VerificationCode的Action,代码如下:
/// <summary> /// 绘制验证码 /// </summary> /// <returns></returns> public ActionResult VerificationCode() { int _verificationLength = 6; int _width = 100, _height = 20; SizeF _verificationTextSize; Bitmap _bitmap = new Bitmap(Server.MapPath("~/Skins/Common/Texture.jpg"),true); TextureBrush _brush = new TextureBrush(_bitmap); //获取验证码 string _verificationText = Common.Text.VerificationText(_verificationLength); //存储验证码 Session["VerificationCode"] = _verificationText.ToUpper(); Font _font = new Font("Arial", 14, FontStyle.Bold); Bitmap _image = new Bitmap(_width, _height); Graphics _g = Graphics.FromImage(_image); //清空背景色 _g.Clear(Color.White); //绘制验证码 _verificationTextSize = _g.MeasureString(_verificationText, _font); _g.DrawString(_verificationText,_font,_brush,(_width-_verificationTextSize.Width)/2,(_height-_verificationTextSize.Height)/2); _image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); return null; }