简体   繁体   中英

How to set ASP.NET session variable?

I am new to ASP.NET and I am trying to set session variable. I have one form (SelectPlayer.aspx) where I am trying to set the session but when I try to see the result on second page it does not show me any value. Below is my code.

SelectPlayer.aspx

public partial class SelectPlayer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["player1"] == null)
        {   
            lblSelectPlayer.Text = "Select Player 1";
        }
    }

    protected void btnSelect_Click(object sender, EventArgs e)
    {            
        Session["player1"] = "PlayerSession";                
        Response.Redirect("Score.aspx");          
    }

}    

Score.aspx

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["player1"] == null)
        {
            Response.Redirect("SelectPlayer.aspx");
        }  
    }

Change Response.Redirect("Score.aspx"); to Response.Redirect("Score.aspx", true);

The second parameter of a redirect indicates that you want to end the response. I've found in the past that setting a Session directly before doing a redirect without this second parameter can cause issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM