《学习MVC3(二)——创建自己的第一个网页:实现用户登陆(1)》由于图片太多了,文章太长,所以就分开写了,紧接上一篇,在上一篇文章中,搭起了程序的一个框架,下面我们开始一点点的在里面添加内容。
第一步:在登陆界面的左上角显示登陆的状态:登陆/退出,因为每个界面都要求在左上角显示这个状态,所以这个状态应该单独写在一个共享页面中,然后写在模板中。
View——Shared——鼠标右键点击——添加View:_LogOnPartial.cshtml
View Code
@if(Request.IsAuthenticated) {
<text >Welcome <b>@Context.User.Identity.Name</b>!
[@Html.ActionLink("退出", "LogOff", "Account") ]</text>
}
else {
@:[ @Html.ActionLink("登陆", "LogOn", "Account") ]
}
模板 _Layout.cshtml的代码如下
View Code
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
</head>
<body>
<div id="logindisplay" style=" margin:20px">
@Html.Partial("_LogOnPartial")
</div>
@RenderBody()
</body>
</body>
</html>
第二步:在Models中添加Account.cs:实现对数据库的操作:读取数据库的值,或者往数据库里面写值,代码如下
View Code
public class Account {
public interface IFormsAuthenticationService {
void SignIn(string userName, bool createPersistentCookie);
void SignOut();
}
public class FormsAuthenticationService : IFormsAuthenticationService {
public void SignIn(string userName, bool createPersistentCookie) {
if(String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut() {
FormsAuthentication.SignOut();
}
}
private static Account initial = new Account();
public static Account Initial { get { return initial; } }
public bool ValidateUser(Users model) {
using(AccountEntities db = new AccountEntities()) {
Users result = db.Users.FirstOrDefault(m => m.Name == model.Name);
if(result != null) {
if(result.Password == model.Password ) {
return true;
} else { return false; }
} else { return false; }
}
}
public bool RegisterUser(Users model) {
using(AccountEntities db = new AccountEntities()) {
if(model != null) {
Users aa = new Users();
aa.Password = model.Password;
aa.Name = model.Name;
aa.Email = model.Email;
db.AddToUsers(aa);
db.SaveChanges();
return true;
}
}
return false;
}
}
第三步:在AccountController.cs中添加注册,登陆,退出方法,代码如下:
View Code
public class AccountController : Controller {
public MyLogin.Models.Account.IFormsAuthenticationService FormsService { get; set; }
protected override void Initialize(RequestContext requestContext) {
if(FormsService == null) { FormsService = new MyLogin.Models.Account.FormsAuthenticationService(); }
base.Initialize(requestContext);
}
public ActionResult Index() {
return View();
}
public ActionResult LogOn() {
return View();
}
public ActionResult Register() {
return View();
}
[HttpPost]
public ActionResult Register(Users model) {
if(ModelState.IsValid) {
if(Account.Initial.RegisterUser(model)) {
FormsService.SignIn(model.Name, true);
return RedirectToAction("Index");
}
}
return View(model);
}
[HttpPost]
public ActionResult LogOn(Users model, string returnUrl) {
if(ModelState.IsValid) {
if(Account.Initial.ValidateUser(model)) {
FormsService.SignIn(model.Name, true);
return RedirectToAction("Index", "Account");
} else {
ModelState.AddModelError("", "用户名或密码不正确,请检查后重新输入!");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
public ActionResult LogOff() {
FormsService.SignOut();
return RedirectToAction("Index", "Account");
}
}
第四步:按照上一篇文章中添加View的方法,添加注册 和 登陆界面
登陆界面代码:
View Code
@using MyLogin.Models
@model Users
@{
ViewBag.Title = "登陆";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<style type="text/css">
#Password, #Name,#Email{
background: none repeat scroll 0 0 #FBFBFB;
border: 1px solid #E5E5E5;
font-size: 24px;
margin-bottom: 15px;
margin-right:16px;
margin-left: 16px;
margin-top: 5px;
padding: 3px;
width :90%;
}
label{
font-size:16px;
margin :15px;
}
</style>
<p style="font-size: 15px; text-align:center; margin:15px 0px;">
请输入用户名和密码。如果没有账号请 @Html.ActionLink("注册", "Register") 。
</p>
<div id="login" style=" margin:0 auto;
margin: 0em auto;
padding: 0 0 5em;
390px;
height:200px;
border: 1px solid #C0C0C0;">
<br />
@Html.ValidationSummary(true, "登陆失败, 请重试.")
@using(Html.BeginForm()) {
<p>
@Html.Label("Name", "账号")
<br />
@Html.TextBoxFor(m => m.Name)
</p>
<p>
@Html.Label("Password", "密码")
<br />
@Html.PasswordFor(m => m.Password)
</p>
<p>
<input type="submit" style="margin: 10px 140px 10px; height: 30px; 80px;"
value="登陆" />
</p>
}
</div>
注册界面代码:
View Code
@using MyLogin.Models;
@model Users
@{
ViewBag.Title = "Register";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<style type="text/css">
#Password, #Name,#Email{
background: none repeat scroll 0 0 #FBFBFB;
border: 1px solid #E5E5E5;
font-size: 24px;
margin-bottom: 15px;
margin-right:16px;
margin-left: 16px;
margin-top: 5px;
padding: 3px;
width :90%;
}
label{
font-size:16px;
margin :15px;
}
</style>
<h2 style =" text-align:center;">创建新账户</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.")
<div style=" margin:0 auto;
margin: 0em auto;
padding: 0 0 5em;
390px;
height:290px;
border: 1px solid #C0C0C0;">
<div class="editor-label">
@Html.Label("账号")
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.Name)
@Html.ValidationMessageFor(m => m.Name)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Email)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.Email)
@Html.ValidationMessageFor(m => m.Email)
</div>
<div class="editor-label">
@Html.Label("密码")
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
</div>
<p>
<input type="submit" value="Register" style="margin: 10px 140px 10px; height: 30px; 80px;" />
</p>
</div>
}
到现在一个简单的用户登陆程序完成了,效果如下:
首页如图1
图1
点击左上角的[登陆]进入登陆界面,如图2
图2
点击登陆界面上的 注册,进入注册界面,如图3
图3