1. 程式人生 > >無廢話MVC入門教程九[實戰一:使用者註冊與登陸]

無廢話MVC入門教程九[實戰一:使用者註冊與登陸]

MVC入門系列教程-視訊版本,已入駐51CTO學院,文字+視訊學效果更好哦。視訊連結地址如下: 點我檢視視訊。另外,針對該系列教程博主提供有償技術支援,群號:226090960,群內會針對該教程的問題進行及時解答,公用性問題統一講解。
學習.NET MVC 只看在《無廢話系列》足夠了,《無廢話系列》簡單、快速、直接。

本文目標

一、獨立開發使用者註冊與登陸

本文目錄

一、在檢視中使用驗證碼

二、在檢視中使用下拉列表

三、使用FormCollection接收客戶端傳送的資料

四、效果預覽與程式碼下載

一、在檢視中使用驗證碼

  MVC中的驗證碼即是在Control中輸出一張圖片顯示在View上

在View的img標籤中新增驗證碼地址“/Image/GetCheckCode/(輸入驗證碼的地址)”,頁面程式碼如下:

1   <img id="check_img" alt="驗證碼" src="/Image/GetCheckCode/" height="30" width="80" onclick="App.refreshCheckCode('check_img')" /><span><a
2             href="javascript:App.refreshCheckCode('check_img');">換一換</a></span>

Control中的介面程式碼方法如下:

1   public class ImageController : Controller
2 { 3 public void GetCheckCode() 4 { 5 CreateCheckCodeImage(GenerateCheckCode()); 6 } 7 }

二、在檢視中使用下拉列表

頁面程式碼如下:

1    @Html.LabelFor(user => user.Residential)
2         @Html.DropDownListFor(user => user.Residential, (SelectList)ViewBag.Residential)

Control程式碼如下:

 1   //取出資料,並通過Helper把資料分解
 2    AddressHelper addressHelper = AddressHelper.GetInstance();
 3    addressHelper.GetResidetialItem(GetList());
 4    //使用ViewBag傳到View
 5    ViewBag.Residential = addressHelper.ResidetialItem;
 6    ViewBag.FloorNo = addressHelper.FloorNoItem;
 7    ViewBag.UnitNo = addressHelper.UnitNoItem;
 8    ViewBag.DoorplateNo = addressHelper.DoorplateNoItem;
 9 
10 
11 
12    public class AddressHelper
13     {
14         //單例
15         private AddressHelper() { }
16         private static AddressHelper Instance = new AddressHelper();
17         public static AddressHelper GetInstance()
18         {
19             return Instance;
20         }
21 
22         public SelectList ResidetialItem { get; private set; }
23         public SelectList FloorNoItem { get; private set; }
24         public SelectList UnitNoItem { get; private set; }
25         public SelectList DoorplateNoItem { get; private set; }
26 
27         //獲取小區列表
28         public void GetResidetialItem(List<Model.Address> AddressItem)
29         {
30             List<SelectListItem> ResidetialItem = new List<SelectListItem>();
31             List<SelectListItem> FloorNoItem = new List<SelectListItem>();
32             List<SelectListItem> UnitNoItem = new List<SelectListItem>();
33             List<SelectListItem> DoorplateNoItem = new List<SelectListItem>();
34             foreach (Model.Address address in AddressItem)
35             {
36                 if (address.Type == 1)
37                 {
38                     ResidetialItem.Add(new SelectListItem { Value = address.AddressID.ToString(), Text = address.Name });
39                 }
40                 if (address.Type == 2)
41                 {
42                     FloorNoItem.Add(new SelectListItem { Value = address.AddressID.ToString(), Text = address.Name });
43                 }
44                 if (address.Type == 3)
45                 {
46                     UnitNoItem.Add(new SelectListItem { Value = address.AddressID.ToString(), Text = address.Name });
47                 }
48                 if (address.Type == 4)
49                 {
50                     DoorplateNoItem.Add(new SelectListItem { Value = address.AddressID.ToString(), Text = address.Name });
51                 }
52             }
53             this.ResidetialItem = new SelectList(ResidetialItem.AsEnumerable(), "Value", "Text");
54             this.FloorNoItem = new SelectList(FloorNoItem.AsEnumerable(), "Value", "Text");
55             this.UnitNoItem = new SelectList(UnitNoItem.AsEnumerable(), "Value", "Text");
56             this.DoorplateNoItem = new SelectList(DoorplateNoItem.AsEnumerable(), "Value", "Text");
57         }
58     }

ViewBag.Residential:在Control與View中傳遞資料

@Html.DropDownListFor:接收SelectList型別的資料,取到資料後要把List轉換成該型別,此例在AddressHelper進行的轉換

三、使用FormCollection接收客戶端傳送的資料

MVC中可以使用強型別在Control與View中進行資料傳遞、也可以使用FormCollection接收資料

此例中我們把驗證碼用FormCollection向後臺傳遞,View程式碼如下:

<input type="text" name="checkCode" />

Control中的程式碼如下:

 1         [HttpPost]//註冊時處理回發
 2         public ActionResult Regedit(Model.User user, FormCollection form)
 3         {
 4             //取出資料,並通過Helper把資料分解
 5             AddressHelper addressHelper = AddressHelper.GetInstance();
 6             addressHelper.GetResidetialItem(GetList());
 7             //使用ViewBag傳到View
 8             ViewBag.Residential = addressHelper.ResidetialItem;
 9             ViewBag.FloorNo = addressHelper.FloorNoItem;
10             ViewBag.UnitNo = addressHelper.UnitNoItem;
11             ViewBag.DoorplateNo = addressHelper.DoorplateNoItem;
12 
13             //校驗驗證碼
14             if (form["checkCode"] != null && form["checkCode"].ToString() == Session["CheckCode"].ToString())
15             {
16                 //校驗其他表單元素
17                 if (ModelState.IsValid)
18                 {
19                     DemoRepository.User.Add(user);
20                     MessageBox.ShowAndRedirect(this, "註冊成功,請登陸!", "/User/Login");
21                 }
22             }
23             else
24             {
25                 MessageBox.Show(this, "驗證碼不正確!");
26             }
27             return View();
28         }

四、效果預覽與程式碼下載

1.註冊

2.登陸

3.程式碼下載

資料檔案在資料夾根目錄下,一切盡在不言中,直接看程式碼吧

五、補:Cookies的使用

登陸的時候註冊Cookies

 1         [HttpPost]//登陸時回發處理
 2         public ActionResult Login(Model.User user)
 3         {
 4             if (ModelState.IsValid)
 5             {
 6                 Model.User newUser = Repository.User.UserLogin(user);
 7                 //檢測使用者名稱和密碼
 8                 if (newUser != null)
 9                 {
10                     DateTime Expires = DateTime.Now;
11                     if (user.Remember == true)
12                         Expires = DateTime.Now.AddDays(365);
13 
14                     Dictionary<string, string> CookieValues = new Dictionary<string, string>();
15                     CookieValues.Add("UserID", newUser.UserID.ToString());
16                     CookieValues.Add("UserName", newUser.UserName);
17                     CookieHelper cookieHelper = new CookieHelper();
18 
19                     cookieHelper.SetCookie(CookieValues, Expires);
20                     Response.Redirect("/Manage/Main");
21                 }
22                 else
23                 {
24                     MessageBox.Show(this, "使用者名稱或密碼不正確!");
25                 }
26             }
27             //客戶端顯示
28             return View();
29         }

此處使用cookieHelper幫助類管理Cookies,類程式碼如下:

 1     public class CookieHelper
 2     {
 3         private string name = "User";   //Cookie名稱
 4 
 5         //是否已經被建立
 6         public bool IsCreate
 7         {
 8             get
 9             {
10                 HttpCookie Cookie = HttpContext.Current.Request.Cookies[this.name];
11                 if (Cookie != null)
12                     return true;
13                 else
14                     return false;
15             }
16         }
17 
18         //設定Cookies
19         public void SetCookie(Dictionary<string, string> Values, DateTime Expires)
20         {
21             HttpCookie Cookie = new HttpCookie(this.name);
22             foreach (string key in Values.Keys)
23             {
24                 Cookie.Values.Add(key, Values[key]);
25             }
26             Cookie.Expires = Expires;
27             HttpContext.Current.Response.Cookies.Add(Cookie);
28         }
29 
30         //獲取Cookie
31         public HttpCookie GetCookie()
32         {
33             return HttpContext.Current.Request.Cookies[this.name];
34         }
35 
36         //清空Cookie
37         public void ClearCookie()
38         {
39             HttpCookie Cookie = HttpContext.Current.Request.Cookies[this.name];
40             Cookie.Expires = DateTime.Now.AddDays(-1);
41             HttpContext.Current.Response.Cookies.Add(Cookie);
42         }
43     }

 鑑於@BangQ 的回覆提出的疑問,關於Cookies安全問題,請具體查閱資料。

六、這個例子程式碼比較多,具體請下載程式碼檢視。