How to clear Session when navigating away from one page - c#

I googled this about 1/2 a hour no hit's. Scenario is that, dynamic scripts are saved in string builder whose "string" representation is stored in session. It just happens that when user navigates away from one page to another the script[from session] gets registered using "RegisterStartupScript". The script is registered in PreRender event of the Page. So i would like to clear this script in session while the page navigates away btw rule out a option to create another session variable and clear previous one. It's a overhead :(

Why are you storing this in Session, do you need to maintain this script in between GET requests?
If only postbacks are relevant you could store it in viewstate as this is maintained only when doing a postback.
If you want this string to be available on GET requests too you might want to introduce a different variable which has an identifier identifying the page for which the script is generated. If the requested page doesn't match the control variable you will have to generate a new script.

How is the user navigating away from the page? Can't you use an ASP.NET button instead of a hyperlink, and then do a Redirect in code once you have cleared your session variable?
protected void btnDoSomething_Click(object sender, EventArgs e)
{
Session["Value"] = String.Empty;
Response.Redirect(strURL, false);
}
OR You could add a variable in the query string and check it in the Page_Load event of the target page:
Webform1.aspx?reset=true

Since I cant comment yet, use onUnload().
It fires on full postbacks too. Ajax postbacks dont fire!
What you need to do, is guaranty inside the onUload function that you only clear the session when you want. Like setting a variable isPostBack to true before the postbacks so onUnload sees the variable and doenst send a request to clear the session.

You may use the JavaScript onUnload() and call an AJAX service, that will clear the server side session.

Related

ASP.Net passing textfield value to a label on a different web page

I have a page called webForm1, this page contains a textfield, when a user enters a value, I want the value to show up in a label on webForm2, when I do that, I am getting an error:
Label1 is inaccessible due to its protection level
This is what I am doing in webForm1
webForm2 webform = new webForm2();
webform.Label = textBox1.Text;
Response.redirect("~/webForm2.aspx");
but the above is not working, I am new to programming and not familiar with classes and complicated programming, what is the easiest way to get the value of the textbox in the label?
Thank you.
You can't instantiate the page class (webForm2) in your current page. You'll have to pass the value in another way to the second page and then bind the label. As Jason P says, the ASP.NET framework instantiates the webForm2 page for you, you can't do it yourself.
If the data is not sensitive, use the Query String:
Response.Redirect("~/webForm2.aspx?label=" + textBox1.Text);
This will redirect the user to a page with the url of whatever.com/webForm2.aspx?label=whatevervalue. On the second page, you can pull the text from the query string and bind it to the label:
public void Page_Load(object sender, EventArgs e)
{
Label.Text = Request.QueryString["label"].ToString();
}
Unlike WinForms, you don't instantiate the next form like that. Essentially, your first two lines are incorrect for WebForms. The third line is where you want to focus your attention. You redirect the user to the second form, allowing the framework to take care of instantiating it.
This is because WebForms, despite being "forms", is still an HTTP web application and does everything through requests and responses. By issuing a redirect you are telling the client to abandon the current page and make a new request for the specified page.
There are a number of ways to send a value to this next page. You can store it in some persisted medium (such as a database), you can use session state, etc. Probably the simplest approach at the moment would be to include it on the query string:
Response.Redirect("~/webForm2.aspx?label=" + textBox1.Text);
Then in the next page you'd get the string from:
Request.QueryString["label"]
You may want to URL-encode the text value first, I don't know if Redirect() does that for you. Also keep in mind that this isn't a "secure" transfer of data from one page to the next, because the client has full access to modify values in the URL. So if this is in any way sensitive data then you'll want to look into other approaches. (Keep in mind that "sensitive" could be a relative term... The information itself might not be sensitive but you might be doing system-sensitive things with it on the next page, which we can't know from the code posted.)

viewstate disappears on response.redirect

On my asp.net c# page I have two text boxes(start and end dates) with ajax CalendarExtenders. The user selects a start date and then an end date. On selecting the end date, I bind my grid as shown below;
protected void calEndDate_TextChanged(object sender, EventArgs e)
{
BindGrid();
}
In the grid I have a command button with the following code
protected void gvAllRoomStatus_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Manage")
{
GridViewRow row = gvAllRoomStatus.Rows[Convert.ToInt16(e.CommandArgument)];
int BookingID = Convert.ToInt32(row.Cells[1].Text);
DataClassesDataContext context = new DataClassesDataContext();
Session["BookingID"] = BookingID;
Response.Redirect("CheckIn.aspx");
}
}
When the user goes to that page and clicks the back button all the selected dates and the gridview data disappears. Any ideas why the viewstate is disappearing?
ViewState belongs to the current Page.
Have a look: http://www.codeproject.com/Articles/37753/Access-ViewState-Across-Pages
Yes, we can access the viewstate variables across pages. This is only
possible if Cross Page Posting or Server.transfer is used to redirect
the user to other page. If Response.redirect is used, then ViewState
cannot be accessed across pages.
So you could use Server.Transfer instead or use the Session.
Viewstate to look at it in a very simplified way is to see it as a carbon copy or cache of the last state of the page you are currently on. Therefore doing a redirect to any page, even the same page itself, is essentially a fresh start. The viewstate no longer applies as for all intent and purpose, you are on a new page.
As Tim suggests in his post, either store the required data as a session variable or use a server.transfer.
Take a look here for a nice overview of viewstate:
http://www.codeproject.com/Articles/37753/Access-ViewState-Across-Pages
In my opinion the issue you have is because you make auto post backs with calEndDate_TextChanged using Ajax.
After your submit, when you press the back button the browser can not remember neither can save what you have change with all that auto post data with Ajax calls, and you lose them.
For me remove the Text Change auto post back, remove the Ajax because you do not needed and make a regular full post back when the user submit their data.
Then when you make back with the browser, browser load the previous state and most of the browsers remember what and all the input of the user. Also on that back the viewstate is the same as previous because did not have change from the Ajax.

Unable to get updated value of session variable and Textbox

I am building a web application in asp.net and c#, I am storing text of textbox in Session variable like this:
Session["data"]=TextBox1.Text;
and on the button click event I am redirecting user to another page.In the second page I am using this variable Session["data"] and in page2 there is a back button where I am again Redirecting to page1 where the textbox1 is present.Now on the button click event where I am redirecting to page2 and event is code like this,
Session["data"]=TextBox1.Text;
Response.Redirect("page2.aspx");
now when I am accessing the value of the Session["data"] it is giving me the previous value.As the content of TextBox1 may get changed,these changes have not been shown.
Please tell me where I am going wrong.
I dont think the code you are using is worng. You please make a break point and check it again that the values are assigning correctly
Or
You just set the session to null and then assign the textbox value to it on the click event.
Read this I think Respone.Redirect might be causing you to lose your session data
Don't redirect after setting a Session variable (or do it right)
A problem I see over and over again on the ASP.NET forums is the
following: In a login page, if the user and password have been
validated, the page developer wants to redirect to the default page.
To do this, he writes the following code:
Session["Login"] = true;
Response.Redirect("~/default.aspx");
Well, this doesn't work. Can you
see why? Yes, it's because of the way Redirect and session variables
work. When you create a new session (that is, the first time you write
to a Session variable), ASP.NET sets a volatile cookie on the client
that contains the session token. On all subsequent requests, and as
long as the server session and the client cookie have not expired,
ASP.NET can look at this cookie and find the right session. Now, what
Redirect does is to send a special header to the client so that it
asks the server for a different page than the one it was waiting for.
Server-side, after sending this header, Redirect ends the response.
This is a very violent thing to do. Response.End actually stops the
execution of the page wherever it is using a ThreadAbortException.
What happens really here is that the session token gets lost in the
battle. There are a few things you can do to solve this problem.
First, in the case of the forms authentication, we already provide a
special redirect method: FormsAuthentication.RedirectFromLoginPage.
This method is great because, well, it works, and also because it will
return the user to the page he was asking for in the first place, and
not always default. This means that the user can bookmark protected
pages on the site, among other things. Another thing you can do is use
the overloaded version of Redirect:
Response.Redirect("~/default.aspx", false);
This does not abort the
thread and thus conserve the session token. Actually, this overload is
used internally by RedirectFromLoginPage. As a matter of facts, I
would advise to always use this overloaded version over the other just
to avoid the nasty effects of the exception. The non-overloaded
version is actually here to stay syntactically compatible with classic
ASP.
I don't really see what you want to do here. You say it works (the Session["data"] contains the text of TextBox1?) but you don't see any changes? What changes did you expect? Please give us some more information about this part of the question:
As the content of TextBox1 may get changed,these changes have not been shown.
Thanks.
Update:
Try clearing or remove the session and then refill it.
Session.Remove("data");
Session.Clear();

Pass values from the asp.net controls in one webpage to asp.net controls in another webpage

I have a webpage 'WPwp1.aspx' and another webpage 'FLcourt.aspx'
In WPwp1.aspx i have DropDownList2,DropDownList3,TextBox1,TextBox2,TextBox3 and a LinkButton1
On click of a link button i want to
redirect to FLcourt.aspx.
FLcourt.aspx also has the controls
that are there in
WPwp1.aspx(DropDownList2,DropDownList3,TextBox1,TextBox2,TextBox3)
When user input value in the controls present in WPwp1.aspx and clicks on LinkButton1, the user should be able to see all the values that were being given as input in 'WPwp1.aspx' into the asp.net controls in 'FLcourt.aspx'.
How is it possible to pass values being input in some controls in a webpage to similar controls in another webpage?
Yes, you have several options:
Use Session variables. This is the less scalable way. Just before Response.Redirect, store
your values in Session and get them in the Page_Load of the target page.
Using QueryString. Pass the values in a query string:
Response.Redirect(
string.Format("FLcourt.aspx?value1={0}&value2={1}",
HttpUtility.UrlEncode(value1),
HttpUtility.UrlEncode(value2)));
And in the second page:
var value1 = Request.QueryString["value1"];
UPDATE
Using cookies (the client's browser must have them enabled). Set cookies before Redirect:
Response.Cookies["MyValues"]["Value1"] = value1;
In the target page:
if(Request.Cookies["MyValues"] != null)
{
var value1 = Request.Cookies["MyValues"]["Value1"];
//...
}
(but you have to check that Request.Cookies["MyValues"] is not null before)
You can try this out.
In your source page ("WPwp1.aspx") create properties for each control i.e. DropDownList2,DropDownList3,TextBox1,TextBox2,TextBox3.
Give "PostBackUrl" property of the linkbutton to the page you want to redirect, in your case it will be "FLcourt.aspx".
In the destination page ("FLcourt.aspx") access the previous page with the help of "PreviousPage" class. This class will give you the properties which you have written in point1.
Hope this helps!
Regards,
Samar
See: http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx
To summarize and answer your question directly, you can:
Use a query string.
Get HTTP POST information from the source page.
And since both pages appear to be in the same Web Application, you can also:
Use session state.
Create public properties in the source page and access the property values in the target page.
Get control information in the target page from controls in the source page using the PreviousPage object. This option has a particular performance disadvantage as a call to PreviousPage results in the instantiation of the object and the processing of its life-cycle up to, but not including PreRender.
Sometimes, though, it is simpler to avoid cross-page postbacks and simulate the multiple pages/stages with Panel or MultiView controls.
Use sessions
Use cookies
Use Applications (global)
Post Back URL
Query String
Server.Transfer
Static Variables (global)
http://www.herongyang.com/VBScript/IIS-ASP-Object-Example-Pass-Value-between-Pages.html
its shown how you do it between two pages.

If one page executes a Response.Redirect() to a different web page, can the new page access values in asp.net controls from the original page?

I have a text string value that I'd like to persist from one web page to another without using query strings or the session/view states. I've been trying to get the ASP http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hiddenfield.aspx">HiddenField control to pass information from one web form to a different form.
All the hiddenfield control examples that I've seen is to preserve round trips from the client to the server for the same form.
Is there way for a form to access the ASP controls (and their values) from the previously-rendered form? Or is the initial form simply disposed of in memory by the time the second form executes it's OnLoad method?
Quick answer is no. As others have noted, you can use Server.Transfer and then you can - however this is to be used with caution. It is a "server side redirect" eg.
Your user is on http://mysite.com/Page1.aspx they click a button and you perform a Server.Transfer("Page2.aspx"). Page2.aspx will be rendered in their browser, but the URL will still be Page1.aspx, this can cause confusion and mess up back/forward navigation.
Personally I would only use Server.Transfer as a last resort - in the world of the web, sharing data across pages generally means you need to use a storage mechanism; Cookie, QueryString, Session, Database - take your pick.
You can't get the previous page fields with Response.Redirect.
You can with cross page posting :
if (Page.PreviousPage != null)
{
TextBox SourceTextBox =
(TextBox)Page.PreviousPage.FindControl("TextBox1");
if (SourceTextBox != null)
{
Label1.Text = SourceTextBox.Text;
}
}
If both pages live in the same application you can use Server.Transfer:
firstpage.aspx:
protected void Page_Load(object sender, EventArgs e)
{
Server.Transfer("~/secondpage.aspx");
}
secondpage.aspx:
protected void Page_Load(object sender, EventArgs e)
{
Page previousPage = (Page) HttpContext.Current.PreviousHandler;
Label previousPageControl = (Label) previousPage.FindControl("theLabel");
label.Text =previousPageControl.Text;
}
A somewhat better solution would be implementing an interface on your first page where you expose properties for the values needed by the second page.
I would presume that the Response.Redirect() sends a Location: HTTP header to do a redirect.
As HTTP is stateless, I'd also presume that these variables are inaccessible.
There are however, solutions.
Print a form with hidden fields, and use javascript to submit it
Redirect in the code internally (load up the thing it needs to get to manually)
Store the data in some temporary database table somewhere, and pass along a unique ID
However, from my experience, I can't understand why you might need to do this (other than re-submitting a form after a user authentication - which hopefully you should be able to use method 2 for
Remember, a Response.Redirect instructs the browser to issue another request to the server. So far as the server is concerned, this next request is indistinguishable from any other incoming request. It's certainly not connected to a previous form in any way.
Could you explain your aversion to storage in the session, so we can propose some viable alternatives?

Categories