如何存储到会话中并显示当前用户信息

时间:2018-07-07 13:08:13

标签: c# sql asp.net

公共类UserDA {     私有静态字符串_connStr = ConfigurationManager.ConnectionStrings [“ airmazin”]。ConnectionString;

//update,delete,insert,getuser

public static void UserInsert(User user)
{

    string queryStr = "INSERT INTO Account (username, gender, email, password) values (@username, @gender, @email, @password);";

    SqlConnection conn = new SqlConnection(_connStr);
    SqlCommand cmd = new SqlCommand(queryStr, conn);
    cmd.Parameters.AddWithValue("@username", user.userName);
    cmd.Parameters.AddWithValue("@gender", user.gender);
    cmd.Parameters.AddWithValue("@email", user.email);
    cmd.Parameters.AddWithValue("@password", user.password);

    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();

}

受保护的无效btn_Submit_Click(对象发送者,EventArgs e)     {

    string userName = tb_userName.Text;
    string gender = rbl_gender.SelectedValue.ToString();
    string email = tb_email.Text;
    string password = tb_password.Text;
    User user = new User(userName, gender, email, password);
    UserDA.UserInsert(user);

}

受保护的无效Page_Load(对象发送者,EventArgs e)     {

}

protected void btn_Login_Click(object sender, EventArgs e)
{
    //if (txt_userEmail == null) { }
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["airmazin"].ToString());
    con.Open(); 
    string query = "select count   from Account where email='" + txt_userEmail.Text+ "' and password='" + txt_userPass.Text +"'" ;

   SqlCommand cmd = new SqlCommand(query, con);
    string output = cmd.ExecuteScalar().ToString();
    con.Close();
    if (output == "1")
    {
        // Create a session
        Session["Account"] = txt_userEmail.Text;


        Response.Redirect("User_Profile.aspx");

   }

   else
    {
        Response.Write("<script>alert('Login NOT successful');</script>");
    }
}

protected void btn_loginSignup_Click(object sender, EventArgs e)
{
    Response.Redirect("SignUp.aspx");
}

}

我已将数据插入数据库中,以及如何将其存储到会话中并在个人资料页面上显示当前用户信息(例如:用户名,电子邮件,性别等)。

1 个答案:

答案 0 :(得分:0)

  1. 您可以通过<%= Session [“ Account”]%>
  2. 访问aspx中的会话值
  3. 您应将SqlConnection包装在using语句中,否则,发生异常时不会释放您的连接。

    使用(SqlConnection连接=新的SqlConnection(connectionString)) {  //您的代码 }