模板选Create,模型类选LoginViewModel ,选项选中引用脚本库。完成后代码
@model Ninesky.Web.Areas.Control.Models.LoginViewModel @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta content="width=device-width" /> <title>登录</title> @Styles.Render("~/Content/controlcss") @Scripts.Render("~/bundles/modernizr") </head> <body> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryval") <div> <div> <h2>登录</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div> @Html.EditorFor(model => model.Accounts, new { htmlAttributes = new { @class = "form-control", placeholder = "帐号" } }) @Html.ValidationMessageFor(model => model.Accounts, "", new { @class = "text-danger" }) </div> <div> @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", placeholder = "密码" } }) @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" }) </div> <div> <input type="submit" value="登录" /> </div> } </div> </div> </body> </html>
在AdminController中添加登录的处理方法public ActionResult Login(LoginViewModel loginViewModel)
[AllowAnonymous] [ValidateAntiForgeryToken] [HttpPost] public ActionResult Login(LoginViewModel loginViewModel) { if(ModelState.IsValid) { string _passowrd = Security.SHA256(loginViewModel.Password); var _response = adminManager.Verify(loginViewModel.Accounts, _passowrd); if (_response.Code == 1) { var _admin = adminManager.Find(loginViewModel.Accounts); Session.Add("AdminID", _admin.AdministratorID); Session.Add("Accounts", _admin.Accounts); _admin.LoginTime = DateTime.Now; _admin.LoginIP = Request.UserHostAddress; adminManager.Update(_admin); return RedirectToAction("Index", "Home"); } else if (_response.Code == 2) ModelState.AddModelError("Accounts", _response.Message); else if (_response.Code == 3) ModelState.AddModelError("Password", _response.Message); else ModelState.AddModelError("",_response.Message); } return View(loginViewModel); }
4、注销
在AdminController中添加注销的处理方法public ActionResult Logout()
/// <summary> /// 注销 /// </summary> /// <returns></returns> public ActionResult Logout() { Session.Clear(); return RedirectToAction("Login"); }
完工可以按F5测试了。
登录界面,输入帐号mzwhj 密码123456,登录成功。
登录成功界面。
=====================================================
代码见:https://ninesky.codeplex.com/SourceControl/latest
代码下载:https://ninesky.codeplex.com 点击SOURCE CODE 点击Download下载源文件。