Passing session variable from page to page - c#

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.

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" />

The code you have posted looks fine, so your problem is probably with setup.
Check this link ASP.NET Session State Overview and pay particular attention to the sections on Cookieless SessionIDs and Configuring Session State.

I don't think you added the session. This is how I have done mine.
First Page
protected void btnView_Click(object sender, EventArgs e)
{
foreach (ListItem li in lbxCheckDates.Items)
{
if (li.Selected == true)
{
lblMessage.Text = "";
string checkDate = lbxCheckDates.SelectedItem.Text;
Session.Add("CheckDates", checkDate);
Page.ClientScript.RegisterStartupScript(
this.GetType(), "OpenWindow", "window.open('Paystub.aspx','_newtab');", true);
}
}
}
Second Page
protected void Page_Load(object sender, EventArgs e)
{
string checkDate = (string)(Session["CheckDates"]);
//I use checkDate in sql to populate a report viewer
}
So with yours, I think you need..
protected void submit_Click(object sender, EventArgs e)
{
string name = txtFirstName.Text.Trim();
Session.Add("Name", name);
}
I think what you have in the second page should work, but if it doesn't, add ToString() to it like..
lblName.Text = (string)(Session["name"]).ToString();
Let me know if this helps!

Are you doing a redirect after setting the session variable on the first page, if so you it will not work correctly (unless you know the trick). Checkout this article on making it work. Basically, the way to make this work is to the overload redirect method.
Response.Redirect("~/newpage.aspx", false);
The false parameter prevents .net from terminate processing on the existing page (that actually writes out the session state)

For Second Page
protected void Page_Load(object sender, EventArgs e)
{
if (Session["value"] != null)
{
Label1.Text = Session["value"].ToString();
}
else
{
Label1.Text = "Sorry,Please enter the value ";
}
}

You can use Server.Transfer() instead of Response.Redirect()

For first page, use this:
protected void Button1_Click(object sender, EventArgs e)
{
string value = TextBox1.Text;
Session["value"] = value;
Response.Redirect("~/Sessionpage.aspx");
}

Related

Session variable has old value, needs to update with page redirect

I have session variable that dont update with new value. I have two pages, one were you enter the values and klick on the button and you get redirected to page 2 and there you can check your input, if this is wrong you click back-button and you go back to the first page where you can change the input but now when i click the button to validate again the new value does not show up in the session variable but only the old value. I have been readingabout session for the last day but i just cant find the problem, the behind code is below:
Page1
protected void Page_Load(object sender, EventArgs e)
{
if (this.Session["value1"] != null)
{
lbl1.Text = (String)this.Session["value1"].ToString();
}
}
public string info { get { return lbl1.Text; } }
protected void inputButton_onclick(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
Session["value1"] = info;
Response.Redirect("~/validpage.aspx");
}
}
Page 2
protected void Page_Load(object sender, EventArgs e)
{
if (Session["value1"] != null)
{
lbl2.Text = (String)Session["value1"].ToString();
}
}
protected void BackButton_Click(object sender, EventArgs e)
{
Session["value1"] = lbl2.Text;
Response.Redirect("~/Default.aspx");
}
Maybe i have staired my self blind on this code as to me this should not have this problem it is presenting. Any idea and help will be appreciated.
Every time Page1 loads, lbl1 is set to the contents of the session, unless it's never been set. So when you click the button, the lbl1 is first set back to the content of the session as the page is loaded. You then read this value back & but it back in the session.
try this instead:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback)
{
if (this.Session["value1"] != null)
{
lbl1.Text = (String)this.Session["value1"].ToString();
}
}
}
This says only set the value if we're not postback, ie NOT clicking a button on the page.
Also in page2, there's no need to call ToString AND cast to a string. Do either, not both.

how to avoid re initialization of session value after redirecting to same page

I have intialized some session variables in page load method to zero. Then I am modifying them in button press method. I am using one session variable as a counter but when I am redirecting the page to the same page, the variables are intialized again. Please help me to prevent this re-initialization. I don't want to use static variables.
The scenario is-
protected void Page_Load(object sender, EventArgs e)
{
session["counter"] = 0;
}
protected void Button1_Click(object sender, EventArgs e)
{
int count = (int)session["counter"];
count++;
session["counter"] = count;
response.redirect("same page");
}
Assuming you just want to check for a non set session variable and if so, set it to zero, then you could just do:
protected void Page_Load(object sender, EventArgs e)
{
if(session["counter"] == null) {
session["counter"] = 0;
}
}
There are also a range of client side options you could use, depending on the situation.
Use
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
session["counter"]=0;
}
protected void Button1_Click(object sender, EventArgs e)
{
int count=(int)session["counter"];
count++;
session["counter"]=count;
//remove response.redirect("same page");
}
Your buuton is server side so your page will postback so you do not need to use response.redirect("same page");
If you are indeed redirecting, and not posting back, just check, on page load, if your initial variable has been set? If not, set it. If it is set, ignore setting it.
'set initial value
if session("counter") is nothing then
session("counter") = 0
end if
If you are posting back, you could also use the above, or you could:
If not isPostBack then
session("counter") = 0
end if
You can move that initialisation to a different page. Instead of directly jumping to your "same page" from another part of your application, julp to an "initializer" instead. That page initializes your session variables and immediately redirects to your "same page".
Your "Button_Click" still redirects to "same page", bypassing that initialisation.

Run the button event handler before page_load

I have a table with all the objects I have in my db. I load them in my Page_Load function. I have a text field and a button that when clicking the button, I want the handler of that click to put a new object with the name written in the text field in the db.
Now, I want that what happens after the click is that the page loads again with the new item in the table. The problem is that the button event handler is run after the Page_Load function.
A solution to this would be to use IsPostBack in the Page_Load or use the pre load function. A problem is that if I would have 3 different buttons, I would have to differ between them there instead of having 3 different convenient functions.
Any solutions that don't have this problem?
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["userId"] == null)
Response.Redirect("Login.aspx");
// LOAD DATA FROM DB
}
protected void CreateObject(object sender, EventArgs e)
{
// SAVE THE NEW OBJECT
}
Maybe you should try loading your data during PreRender instead of Load
protected void Page_Load(object sender, EventArgs e)
{
this.PreRender += Page_PreRender
if (Session["userId"] == null)
Response.Redirect("Login.aspx");
}
protected bool reloadNeeded {get; set;}
protected void CreateObject(object sender, EventArgs e)
{
// SAVE THE NEW OBJECT
reloadNeeded = true;
}
protected void Page_PreRender(object sender, EventArgs e)
{
if(reloadNeeded || !IsPostBack)
// LOAD DATA FROM DB
}
You can check the event target and do what you need then:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string eventTarget = Page.Request.Params["__EVENTTARGET"];
if(whatever)
{
//do your logic here
}
}
}
Get control name in Page_Load event which make the post back
Use the Page_PreRenderComplete event to retrieve your table. That way your page will always have the most recent data available after all user events have fired.
Why don't you move what you have in the click event into a new method. Then call that method as the first line in your page load?
An old question but I faced the same problem in my C#/ASP.NET Website with master/content pages: a click on a link on the master page should change a query parameter for a gridview on the content page. As you stated the button click event is handled after Page_Load. But it is handled before Page_LoadComplete (see the information about ASP.NET Page Life Cycle), so you can change the page content there.
In my case I solved the problem by setting a session variable in the click event in the master page, getting this variable in the Page_LoadComplete event in the content page and doing databind based on that.
Master page:
<asp:LinkButton ID="Btn1" runat="server" OnCommand="LinkCommand" CommandArgument="1" >Action 1</asp:LinkButton>
<asp:LinkButton ID="Btn2" runat="server" OnCommand="LinkCommand" CommandArgument="2" >Action 2</asp:LinkButton>
protected void LinkCommand(object sender, CommandEventArgs e)
{
HttpContext.Current.Session["BindInfo", e.CommandArgument.ToString());
}
Content page:
protected void Page_LoadComplete(object sender, EventArgs e)
{
string BindInfo = HttpContext.Current.Session["BindInfo"].ToString();
YourBindDataFunction(BindInfo);
}

ASP.NET C# - How to retain value after Response.Redirect

I'm working in ASP.NET c# application.
I came to a part where I need to retain some value after response.redirect to the same page without using additional QueryString or Session, because Session more or less may burden the server's performance even just a small value.
Below is my code fragment:
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
string id = ddl.SelectedValue;
string id2 = ddl2.SelectedValue;
Response.Redirect("http://sharepoint2007/sites/home/Lists/CustomList/DispForm.aspx?ID=" + id);
}
I wanted to retain the value id2 after the Response.Redirect, I've tried ViewState but seem like after the redirect, it treat the page as new page and ViewState value gone.
Update:
My intention to retain the value after redirect is wanted to bind back the dropdownlist selected value.
Please help.
Thank you in advanced.
using cookies will do the trick:
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
string id = ddl.SelectedValue;
string id2 = ddl2.SelectedValue;
HttpCookie cookie = new HttpCookie("SecondId", id2);
Response.Cookies.Add(cookie);
Response.Redirect("http://sharepoint2007/sites/home/Lists/CustomList/DispForm.aspx?ID=" + id);
}
protected void OnLoad(object sender, EventArgs e)
{
string id2 = Request.Cookies["SecondId"];
//send a cookie with an expiration date in the past so the browser deletes the other one
//you don't want the cookie appearing multiple times on your server
HttpCookie clearCookie = new HttpCookie("SecondId", null);
clearCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(clearCookie);
}
Make use of Session variable will do for you
Code for you
Session["id2"] = ddl2.SelectedValue;
as you are redirecting from one page to another page viewstate is not going to help you , Session varialbe can able to store value till the user logout of site or till session ends, ViewState is helpfull when you are doing autopostback to your page
or
if possible you can attach id2 variable in querystring only as you are doing with id1 variable
besides session, query string, you can also use cookie, application variable and database to persist your data.
You can achieve it using Session or by QueryString
By Session
In your first page:
Session["abc"] = ddlitem;
Then in your next page access the session using:
protected void Page_Load(object sender, EventArgs e)
{
String cart= String.Empty;
if(!String.IsNullOrEmpty(Session["abc"].ToString()))
{
xyz= Session["abc"].ToString();
// do Something();
}
else
{
// do Something();
}
}
-
By QueryString
In your first page:
private void button1_Click(object sender, EventArgs e)
{
String abc= "ddlitem";
Response.Redirect("Checkout.aspx?ddlitemonnextpage" + abc)
}
In your second page:
protected void Page_Load(object sender, EventArgs e)
{
string xyz= Request.QueryString["ddlitemonnextpage"].ToString();
// do Something();
}

Redirect as a fresh request after using Response.Redirect

I am working on an aspx page in VS 2005. I have code like this,
int RepID = 0;
protected void Page_Load(object sender, Eventargs e)
{
if(!Page.Ispostback)
{
get value from database and display it in textbox;
}
else
{
}
}
protected void Save_OnClick(object sender, Eventargs e)
{
Update Database with modified textbox Text ;
Response.Redirect(//To the same page);
}
After the Response.Redirect, i was looking for the page to refresh and get the modified value from database. Instead, it uses the else loop in Page_load and displays the old value because it doesn't go into the if loop as it is the Postback. How can i display from database after the response.redirect is used. I know i am missing a logic but i am not sure what? Thanks alott guys..
Delete
Response.Redirect(//to same page);
Your Save button click should post back to the same page it is on.

Categories

Resources