Asp.Mvc 2.0实现用户登录与注销功能实例讲解(2) 这一节讲解下ASP.MVC 2.0的用户登录与注销功能,先讲登录,后说注销。我们这个系列讲的用户登录方式都是FORM表单验证方式。在讲之前先给大家说下<%:%>的功能,<%:%>与<%=%>功能一样,用来动态输出内容。 一、登录 1. 建立MODEL 登录的时候,我们一般只要验证用户名和密码,还有是否保存登录COOKIE,所以我们建立一个MODEL登录类,只需包括3个字段就可以。 /// /// 用户登录MODEL /// public class Login { /// /// 用户名 /// [DisplayName("用户名")] public string UserName { get; set; } /// /// 密码 /// [DisplayName("密码")] public string UserPwd { get; set; } /// /// 是否保存COOKIE /// [DisplayName("记住我")] public bool RememberMe { get; set; } 2.建立VIEW页面 同样登录的VIEW页面,同样建立一个强类型的页面,之所以喜欢建立强类型的页面,是因为页面和MODEL相关联,在页面中直接可以使用MODEL。此时页面的视图数据类应选择MvcLogin.Models.Login。 <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %> Login
<%if (ViewData["msg"] != null) {%> <%:ViewData["msg"].ToString()%> <%} %>
<%Html.BeginForm();%>
用户登录
<%:Html.LabelFor(m=>m.UserName) %> <%:Html.TextBoxFor(m=>m.UserName)%>
<%:Html.LabelFor(m=>m.UserPwd) %> <%:Html.PasswordFor(m=>m.UserPwd) %>
<%:Html.LabelFor(m=>m.RememberMe) %> <%:Html.CheckBoxFor(m=>m.RememberMe) %>
<%Html.EndForm(); %>
Html.CheckBoxFor用来生成一个复选框按钮 3.建立controller 同样我们在controller中建立两个login方法,一个用来展现页面,一个用来点击登录按钮后判断用户名和密码 public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(Models.Login model) { if (new Models.SqlHelper().UserLogin(model)) { //如果用户名存在,转向主页 FormsService.SignIn(model.UserName,model.RememberMe); return RedirectToAction("index"); } else { //登录失败,转向登录页面 ViewData["msg"] = "登录失败"; return View(model); } } 第二个Login方法前面有HTTPPOST属性,所以只能接受POST请求 4.SQLHELPER中添加判断用户名和密码的方法 /// /// 判断用户登录是否成功 /// /// /// public bool UserLogin(Login model) { strUserExist = string.Format(strUserExist, model.UserName, model.UserPwd); SqlConnection con = new SqlConnection(conStr); con.Open(); SqlCommand cmd = new SqlCommand(strUserExist, con); SqlDataAdapter adp = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adp.Fill(ds); con.Close(); if (ds != null && ds.Tables[0].Rows.Count > 0) { return true; } return false; } 5.运行登录页面 此时我们在页面中输入URL,就会转向登录页面, 效果如下: 点击登录,登录成功后转向首页,登录失败返回本页面,并显示提示信息。 点击登录的时候,是POST提交方式,会调用publicActionResult Login(Models.Login model)方法。 登录失败页面如下 登录成功页面如下 二.注销 登录成功后,转向首页,在首页上我们会生成注销连接。

<%if (Request.IsAuthenticated) {%> 欢迎您<%:Page.User.Identity.Name%>! <%:Html.ActionLink("注销", "LoginOff")%> <%} else {%> <%:Html.ActionLink("登录", "Login")%> <%} %>

这里介绍下Html.ActionLink方法, Html.ActionLink用来生成一个链接,第一个参数代表链接的问题,第二个参数代表的是actionname,可以理解为链接的页面。 由以上代码可以看出,注销链接指向LoginoFF.,也就是controller中的loginoff action方法,所以我们在controller中添加一个一个loginoff方法,执行完loginoff方法后,会转向INDEX首页 /// /// 用户注销 /// /// public ActionResult LoginOff() { FormsService.SignOut(); return RedirectToAction("index"); } 以上就是Asp.Mvc 2.0实现用户登录与注销功能实例讲解,大家可以在自己的网站上进行实践了,希望在此基础上可以有所创新和完善。