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


朋友炒股兩個月賺了10萬,我幫他推廣一下公眾號,把錢用來投資總比放銀行連通貨膨脹都跑不過里強硬核離職,在家炒股 ,這是他每天的日志,有些經驗是花錢也買不到的。

本文目標

一、獨立開發用戶注冊與登陸

本文目錄

一、在視圖中使用驗證碼

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

三、使用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安全問題,請具體查閱資料。

六、這個例子代碼比較多,具體請下載代碼查看。

版權:http://www.cnblogs.com/iamlilinfeng


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM