2016-05-17 43 views
0

我有三個頁面(Home, Register, Store)彼此鏈接。主頁提供登錄選項,用於保存在數據庫中的預先存在的用戶。如果只有登錄成功,有人可以訪問商店頁面,否則單擊商店頁面不會執行任何操作(只需粘貼在同一主頁中)。如果只有已登錄的用戶,如何重定向或訪問頁面

Home.aspx.cs:

protected void Button1_Click(object sender, EventArgs e)//login 
    { 
     SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\lab1.mdf;Integrated Security=True"); 
     SqlCommand cmd = new SqlCommand(); 
     cmd.CommandText = "SELECT * FROM userdata WHERE username='" + TextBox1.Text + "'"; 
     cmd.Connection = conn; 
     //cmd.ExecuteNonQuery(); 

     SqlDataAdapter da = new SqlDataAdapter(cmd); 
     DataTable dt = new DataTable(); 
     da.Fill(dt); 
     if (dt.Rows.Count > 0) 
     { 
      //Session["name"] = dt.Rows[0]["userName"].ToString(); 
      Response.Redirect("Store.aspx?name=" + TextBox1.Text + ""); 
     } 
     else 
     { 
      Response.Redirect("Register.aspx"); 
     } 
    } 

Home.aspx:

<p><a href="Home.aspx">Home</a> <a href="Register.aspx">Register</a> <a href="Store.aspx">Store</a></p> 

Store.aspx:

<p><a href="Home.aspx">Home</a> <a href="Register.aspx">Register</a> <a href="Store.aspx">Store</a></p> 
+0

創建一個會話,並檢查是否會話都有價值或無效,則讓用戶在商店頁面重定向還有他的主頁,簡單 –

回答

0

有兩種方式一種是創建一個類,定義一個靜態字段和其他方式是會話,但我更喜歡登錄會話

首先您將創建一個會話如

if (dt.Rows.Count > 0) 
     { 

      Response.Redirect("Store.aspx?name=" + TextBox1.Text + ""); 
      Session["UserAuthentication"] = true; 
     } 

現在檢查每一頁上,或者如果你有在.cs文件母版頁添加代碼,如果真的還是假的檢查天氣UserAuthentication,並記得添加代碼到Page_Load在CS文件

的增加一個檢查

if (Convert.ToBoolean(Session["UserAuthentication"]) == false) 
    { 
     Response.Redirect("Register.aspx"); 
    } 
相關問題