2017-02-18 269 views
0

我想學習MVC編碼,但我有一個最後一個小問題。首先登錄不起作用,但第二次登錄是工作。它每次都是這樣工作的。首先登錄不工作,但第二次登錄工作

我的控制器代碼:

public ActionResult Login() 
    { 
     if (Session["UserID"] != null) 
     { 
      Response.Redirect("/Home/Index"); 
     } 
     return View(); 
    } 

[HttpPost] 
public ActionResult Login(string txtUsername, string txtPassword) 
    {    
     Customer loggedInUser = db.Customers.Where(x=> x.Username == txtUsername && x.Password == txtPassword).FirstOrDefault(); 
     if (loggedInUser == null) 
     { 
      Response.Write("<script>alert('Please check your username and password.')</script>"); 
      return View(); 
     } 
     else 
     {     
      Session["UserID"] = loggedInUser.ID; 
      Response.Redirect("/Home/Index"); 
      return View(); 
     }      
    } 

我使用這個會話[「用戶名」]索引頁上要明白,我登錄

我的索引視圖代碼:

@section Login{ 

    @if (Session["UserID"] == null) 
    { 
     <li><a href="/Home/Login"><span class="glyphicon glyphicon-log-in"> </span> &nbsp Log In</a></li> 
     <li><a href="/Home/Register"><span class="glyphicon glyphicon-plus"> </span> Create an Account</a></li> 
    } 
    else 
    {  
     int userID = (int)Session["UserID"]; 
     <li><a href="/Home/UserDetail/@userID"><span class="glyphicon glyphicon-user"> </span> User Detail</a></li> 
     <li><a href="/Home/Orders"><span class="glyphicon glyphicon-gift"> </span> &nbsp Orders</a></li> 
     <li><a href="/Home/LogOut"><span class="glyphicon glyphicon-log-out"> </span> &nbsp Log Out</a></li> 
    } 
} 

我用VS上的斷點來研究它。在第一次登錄嘗試中,Session [「UserID」]在控制器上填充,但在第一次登錄嘗試時,在Index View頁面上Session [「UserID」]看起來類似於null。我給第二次嘗試,這次會話[「用戶ID」]在索引視圖頁面上不爲空。

感謝任何人的幫助,所以對不起我的英語不好。

回答

0

OK,我已經解決了這個問題,這樣

[HttpPost] 
public ActionResult Login(string txtUsername, string txtPassword) 
    {    
     Customer loggedInUser = db.Customers.Where(x=> x.Username == txtUsername && x.Password == txtPassword).FirstOrDefault(); 
     if (loggedInUser == null) 
     { 
      Response.Write("<script>alert('Please check your username and password.')</script>"); 
      return View(); 
     } 
     else 
     {     
      Session["UserID"] = loggedInUser.ID; 
      //Response.Redirect("/Home/Index"); that's not good way 
      return Redirect("/Home/Index"); //this is the good way 
     }      
    }