Asp.Mvc 2.0实现用户登录与注销功能实例讲解(2) |
|
本文标签:Asp.Mvc,用户登录与注销 这一节讲解下ASP.MVC 2.0的用户登录与注销功能,先讲登录,后说注销 。我们这个系列讲的用户登录方式都是FORM表单验证方式 。在讲之前先给大家说下<%:%>的功能,<%:%>与<%=%>功能一样,用来动态输出内容 。
/// <summary>
/// 用户登录MODEL
/// </summary>
public class Login
{
/// <summary>
/// 用户名
/// </summary>
[DisplayName("用户名")]
public string UserName
{
get;
set;
}
/// <summary>
/// 密码
/// </summary>
[DisplayName("密码")]
public string UserPwd
{
get;
set;
}
/// <summary>
/// 是否保存COOKIE
/// </summary>
[DisplayName("记住我")]
public bool RememberMe
{
get;
set;
}
2.建立VIEW页面
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcLogin.Models.Login>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Login</title>
</head>
<body>
<div style="font-size:15pt;color:Red;">
<%if (ViewData["msg"] != null)
{%>
<%:ViewData["msg"].ToString()%>
<%} %>
</div>
<div>
<%Html.BeginForm();%>
<table>
<tr>
<td></td>
<td>用户登录</td>
</tr>
<tr>
<td><%:Html.LabelFor(m=>m.UserName) %></td>
<td><%:Html.TextBoxFor(m=>m.UserName)%></td>
</tr>
<tr>
<td><%:Html.LabelFor(m=>m.UserPwd) %></td>
<td><%:Html.PasswordFor(m=>m.UserPwd) %></td>
</tr>
<tr>
<td><%:Html.LabelFor(m=>m.RememberMe) %></td>
<td><%:Html.CheckBoxFor(m=>m.RememberMe) %></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="登录" /></td>
</tr>
</table>
<%Html.EndForm(); %>
</div>
</body>
</html>
Html.CheckBoxFor用来生成一个复选框按钮
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请求
/// <summary>
/// 判断用户登录是否成功
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
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.运行登录页面
点击登录,登录成功后转向首页,登录失败返回本页面,并显示提示信息 。
登录成功页面如下
二.注销
<p style="font-size:15pt; color:Red;">
<%if (Request.IsAuthenticated)
{%>
欢迎您<%:Page.User.Identity.Name%>!
<%:Html.ActionLink("注销", "LoginOff")%>
<%}
else
{%>
<%:Html.ActionLink("登录", "Login")%>
<%} %>
</p>
这里介绍下Html.ActionLink方法,
<span style="font-family:Microsoft YaHei;font-size:16px;"> </span>/// <summary>
/// 用户注销
/// </summary>
/// <returns></returns>
public ActionResult LoginOff()
{
FormsService.SignOut();
return RedirectToAction("index");
}
以上就是Asp.Mvc 2.0实现用户登录与注销功能实例讲解,大家可以在自己的网站上进行实践了,希望在此基础上可以有所创新和完善 。 |