DanaZhangMvcCms 第一节用户登录
1.用户登录
先看一下解决方案
接下来我们建一个名为Users的Model
public class Users { public Users() { } [Key] [DisplayName("编号")] public int Id { get; set; } [DisplayName("用户名")] [Required(ErrorMessage = "用户名不得为空")] [DisplayFormat(ConvertEmptyStringToNull = false)] public string Name { get; set; } [DisplayName("密码")] [Required(ErrorMessage = "密码不得为空")] [DisplayFormat(ConvertEmptyStringToNull = false)] public string Password { get; set; } [DisplayName("姓名")] [Required(ErrorMessage = "姓名不得为空")] [DisplayFormat(ConvertEmptyStringToNull = false)] public string RealName { get; set; } [DisplayName("级别")] [Required(ErrorMessage = "级别不得为空")] [DisplayFormat(ConvertEmptyStringToNull = false)] public string RankId { get; set; } [DisplayName("管理用户?")] [Required(ErrorMessage = "管理用户?不得为空")] [DisplayFormat(ConvertEmptyStringToNull = false)] public string IsPower { get; set; } [DisplayName("是否激活")] [Required(ErrorMessage = "是否激活不得为空")] [DisplayFormat(ConvertEmptyStringToNull = false)] public string IsActive { get; set; } [DisplayName("所属地区")] [Required(ErrorMessage = "所属地区不得为空")] [DisplayFormat(ConvertEmptyStringToNull = false)] public string RegionId { get; set; } [DisplayName("手机号")] [Required(ErrorMessage = "手机号不得为空")] [DisplayFormat(ConvertEmptyStringToNull = false)] public string Mobil { get; set; } [DisplayName("电子邮件")] [Required(ErrorMessage = "电子邮件不得为空")] [DisplayFormat(ConvertEmptyStringToNull = false)] public string Email { get; set; } }
然后是BLL中的代码,Resposity 模式我暂时没用
public class UsersServices { DanaZhangMvcCmsContext _db = new DanaZhangMvcCmsContext(); public IQueryable<Users> Get() { var model = _db.Users.OrderBy(a => a.Id); return model; } public Users Get(int Id) { var item = new Users(); item = _db.Users.SingleOrDefault(a => a.Id.Equals(Id)); return item; } public Users Get(string name) { var item = new Users(); item= _db.Users.SingleOrDefault(a => a.Name.Equals(name)); return item; } public string GetName(int Id) { string name = "您好,游客"; var user = Get(Id); if (user != null) name = user.Name; return name; } public bool CheckUser(int Id, string password) { password = Common.DESEncrypt.Encrypt(password); return Get(Id).Password.Equals( password); } public bool IsDuplicate(string name) { bool isDuplicate = false; var item = _db.Users.SingleOrDefault(a => a.Name == name); if (item != null) isDuplicate = true; return isDuplicate; } public bool IsDuplicateButSelf(int Id, string name) { bool isDuplicate = false; var item = _db.Users.SingleOrDefault(a => a.Id != Id && a.Name == name); if (item != null) isDuplicate = true; return isDuplicate; } public void Save(int Id, ref Users item) { _db.Users.Add(item); _db.SaveChanges(); } public void DeleteObject(int Id) { _db.Users.Remove(_db.Users.Single(a => a.Id == Id)); _db.SaveChanges(); } }
在写Controller中的内容
public class AccountController : Controller { // // GET: /Account/ UsersServices _UsersBLL = new UsersServices(); public ActionResult LogOn() { return View(); } [HttpPost] public ActionResult LogOn(LogOnModel item) { bool isPower = true; string ip = Request.UserHostAddress; if (!ModelState.IsValid) { return View(item); } var item1 = _UsersBLL.Get(item.Name); if (item1 != null) { if (_UsersBLL.CheckUser(item1.Id, item.Password)) { FormsAuthentication.SetAuthCookie(item1.Name.ToString(),false); if (isPower) { return Redirect("/Admin"); } else { if (Request["ReturnUrl"] != null) { return Redirect(Request["ReturnUrl"]); } else { return Redirect("/"); } } } else { ModelState.AddModelError("", "用户名不存在或密码错误!"); } } else { ModelState.AddModelError("", "用户名不存在或密码错误!"); } return View(item); } public virtual ActionResult LogOff() { FormsAuthentication.SignOut(); return Redirect("/"); } #region 生成验证码图片 [OutputCache(Location = OutputCacheLocation.None, Duration = 0, NoStore = false)] public ActionResult SecurityCode() { string oldcode = TempData["SecurityCode"] as string; string code = CreateRandomCode(5); TempData["SecurityCode"] = code; return File(CreateValidateGraphic(code), "image/Jpeg"); } private byte[] CreateImage(string checkCode) { int iwidth = (int)(checkCode.Length * 12); System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20); Graphics g = Graphics.FromImage(image); Font f = new System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Bold); Brush b = new System.Drawing.SolidBrush(Color.White); g.Clear(Color.Blue); g.DrawString(checkCode, f, b, 3, 3); Pen blackPen = new Pen(Color.Black, 0); Random rand = new Random(); for (int i = 0; i < 5; i++) { int x1 = rand.Next(image.Width); int x2 = rand.Next(image.Width); int y1 = rand.Next(image.Height); int y2 = rand.Next(image.Height); g.DrawLine(new Pen(Color.Silver, 1), x1, y1, x2, y2); } System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); return ms.ToArray(); } private string CreateRandomCode(int codeCount) { string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z"; string[] allCharArray = allChar.Split(','); string randomCode = ""; int temp = -1; Random rand = new Random(); for (int i = 0; i < codeCount; i++) { if (temp != -1) { rand = new Random(i * temp * ((int)DateTime.Now.Ticks)); } int t = rand.Next(35); if (temp == t) { return CreateRandomCode(codeCount); } temp = t; randomCode += allCharArray[t]; } return randomCode; } /// <summary> /// 创建验证码的图片 /// </summary> public byte[] CreateValidateGraphic(string validateCode) { Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 16.0), 27); Graphics g = Graphics.FromImage(image); try { //生成随机生成器 Random random = new Random(); //清空图片背景色 g.Clear(Color.White); //画图片的干扰线 for (int i = 0; i < 25; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } Font font = new Font("Arial", 13, (FontStyle.Bold | FontStyle.Italic)); LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); g.DrawString(validateCode, font, brush, 3, 2); //画图片的前景干扰点 for (int i = 0; i < 100; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } //画图片的边框线 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); //保存图片数据 MemoryStream stream = new MemoryStream(); image.Save(stream, ImageFormat.Jpeg); //输出图片流 return stream.ToArray(); } finally { g.Dispose(); image.Dispose(); } } #endregion }
然后就是View了
@model DanaZhangMvcCms.Model.LogOnModel @{ Layout = null; } <!DOCTYPE html> <html> <head> <title>用户登录</title> <link href="/scripts/ui/skins/Aqua/css/ligerui-all.css" rel="stylesheet" type="text/css" /> <link href="/Content/image/style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="/scripts/jquery.min.js"></script> <script type="text/javascript" src="/scripts/jquery.validate.js"></script> <script type="text/javascript" src="/scripts/messages_cn.js"></script> <script type="text/javascript" src="/scripts/ui/js/ligerBuild.min.js"></script> <script type="text/javascript" src="/scripts/function.js"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> <script type="text/javascript"> //表单验证 $(function () { //检测IE if ($.browser.msie && $.browser.version == "6.0") { window.location.href = 'ie6update.html'; } $('#name').focus(); }); </script> </head> <body> <div class="login_div"> @Html.ValidationSummary(true) <form action="@Url.Action("LogOn","Account")" method="post"> <div class="login_box"> <div class="login_logo">LOGO</div> <div class="login_content"> <dl> <dt>登录账号:</dt> <dd> <input name="Name" type="text" id="Name" style="width:130px;" /> @Html.ValidationMessageFor(m => m.Name) </dd> </dl> <dl > <dt>登录密码:</dt> <dd> <input name="Password" type="password" id="Password" class="login_input required" style="width:130px;" /> </dd> </dl> <dl> <dt>验证码:</dt> <dd> <input name="txtCode" type="text" maxlength="6" id="txtCode" class="login_input required" style="width:55px;text-transform:uppercase;" /> <img src="SecurityCode" width="70" height="22" alt="点击切换验证码" title="点击切换验证码" style=" margin-top:2px; vertical-align:top;cursor:pointer;" onclick="ToggleCode(this, 'SecurityCode');return false;" /> </dd> </dl> </div> <div class="login_foot"> <div class="right"><input type="submit" name="btnSubmit" value="登 录" id="btnSubmit" class="login_btn" /></div> </div> </div> </form> <div class="login_copyright">Copyright © 2009 - @System.DateTime.Now.Year DanaZhang All Rights Reserved.<br />DanaZhang 版权所有</div> </div> </body> </html>
登录现在就算完成了,看一下我们的界面