Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing session variable from page to page

I'm wondering what is my issue on passing a variable from page to page using asp.net session.

I've stripped the code down to just one text box to see whats going on. I'm just trying to take the value of a text box and display it on a confirmation page. When the button is clicked it transfers me to the second page but there label is blank. Yes my post back url is pointing to the second page.

Here is the button click:

protected void submit_Click(object sender, EventArgs e)
{
    string name = txtFirstName.Text.Trim();
    Session["name"] = name;
}

Here is the page load of the second page:

protected void Page_Load(object sender, EventArgs e)
{
    lblName.Text = (string)(Session["name"]);
}

Unless I've been looking at this to long and missed something. I've already read "How to: Read Values from Session State" from MSDN.

like image 703
Troy Bryant Avatar asked Oct 29 '13 20:10

Troy Bryant


1 Answers

You say that you've set the PostBackUrl to your second page. If you're going to do it that way, you need to use Page.PreviousPage to get access to your textbox. But this is the easiest way:

Firstly, leave the PostBackUrl alone. Setting the PostBackUrl to your second page means that you're telling the SECOND PAGE to handle your button click, not the first page. Hence, your session variable never gets set, and is null when you try to pull it.

This should work for ya.

And yes, you can also do this with a QueryString, but if its something that you don't want the user to see/edit, then a Session variable is better.

 protected void submit_Click(object sender, EventArgs e)
 {
      string name = txtFirstName.Text.Trim();
      Session["name"] = name;
      Response.Redirect("PageTwo.aspx");
 }

Then in the second page (You don't REALLY need the ToString()):

 protected void Page_Load(object sender, EventArgs e)
 {
      if (Session["name"] != null)
      {
           lblName.Text = Session["name"].ToString();
      }
 }

EDIT -- Make sure that your button click actually gets fired. Someone can correct me wrong on this, as I do most of my work in VB.NET, not C#. But if you don't specify the OnClick value, your function won't get called.

 <asp:Button ID="Button1" runat="server" Text="Click Me!" OnClick="submit_Click" />
like image 104
CaptainStealthy Avatar answered Sep 24 '22 10:09

CaptainStealthy