Browse Tag

asp.net

ASP.NET passing data between pages

Today I was working on a senario where I wanted to pass an ID to another page after a postback had occurred. Usually I would do this using a redirect with the ID appended behind the URL as query string, like this.

// In page2.aspx
protected void Button1_Click(object sender, EventArgs e)
{
    // Did something here
    string passinId = txtId.Text;
    Response.Redirect("/Page1.aspx?id=" + passinId);
}

And then in Page1.aspx, I do this to get the ID.

// In Page1.aspx
protected void Page_Load(object sender, EventArgs e)
{
    String s_id = Request.QueryString["id"];
    if(null != s_id)
    {
        // do something
    }
}

However, in this special case, I’m actually loading Page2.aspx using AJAX within a modal window in Page1.aspx. Page1.aspx has many links to load Page2.aspx (I’ll skip the long story), so having the ID in the address bar as a query string will make it look very confusing to the user.
I find Session quite useful here: it allows me to pass the ID between pages yet not showing it in the address bar. Of course, security is not of concern here since I’ve been showing it in the address bar anyway.
So in Page2.aspx, instead of appending the ID behind the URL, I do this.

// In Page2.aspx
protected void Button1_Click(object sender, EventArgs e)
{
    // Did something here
    string passinId = txtId.Text;
    Session["SpecialKeyName"] = passinId
    Response.Redirect("/Page1.aspx");
}

Then in Page1.aspx, I get the ID like this.

// In Page1.aspx
protected void Page_Load(object sender, EventArgs e)
{
    if (Session["SpecialKeyName"] != null)
    {
        //get the Session value
        string s_id = (string)(Session["SpecialKeyName"]);
        Session.Remove("SpecialKeyName");
        // Do something
    }
}

I make it a point to delete the session after use since I only want to use it whenever it’s available. If it’s not available, I will show some default data.

This is not the only way, but it definitely helps me solve my problem.

Read up here on MSDN for more information on Session, different types of approaches as well as some tips and warnings of each approach.

Another good read about ASP.NET Session State on MSDN here.