Executing c# commands when navigating away from a certain page - c#

I've checked around the entire web and could not find an answer for this.
For my project, i made a form to delete an account in a website, but i want it to relocate you to another page saying "the account x had been deleted successfully."
Thus, i need to keep the Sessions still set for the user name, to be able to write the name of the user instead of that "x", and then when they navigate away, that Session variable will be reset to nothing.
But how?
Of course, i can set on every button possible to delete it, but that's just stupid.
Is there a way to run c# commands when you navigate away from a certain page?
Edit: All this time i've been looking strictly c#, but i now found out there's this thing called unload in javascript.
Question is: how can i reset the session variable using that?

You may simply get the username from session on the c# code, assign it to a textbox and then reset the session variable. Put the entire code in the page_load event.
For the "get away from this page", if you have a common masterpage or base page, you may check if the previous page (Getting the HTTP Referrer in ASP.NET) is the page for delete account and if yes clean the session variable

If you have a 'Delete My Account' button on a page, simply post back on the button click.
In the button click's event handler assign what values you wish to local variables from the current Session - Name, Date of Membership, Expiry Date etc.
Abandon the Session (Session.Abandon()) - or even clear all settings in it if that is a better option.
Use the variables to populate any labels, spans etc. on your returning web page. This could be the same page - or a redirect to a different page. If redirecting, pass the values you need to the next page to use in your output.
If you will be able to post back to the same pages that were accessing the Session variables, then ensure that you check that the Session is available and that the variables you are looking up exist (i.e. null check everything).

Related

When might you choose to use ViewState over the Session?

I have a doubt why we use ViewState because Session can keep its state throughout the application. Then why is the need for ViewState which can keep the state only in a single Page?
First Thing first is to know what is
View State
Is information of a particular page in webforms. It is stored in hidden field. It is used to maintain that the page remembers what he did on it the last time.
Session
Is information that is related to a specific session.i.e. certain browser
now coming to your question
When to use and not use is a cluster F......
as all have their specific pros and cons specially ViewSate is more a con I guess since the MVC was introduced.
One can use viewstate to store values to remember when its page have a post back as every time, when a page is in a post back stage it removes all the values of user controls .i.e. like Label and TextBox in asp.net . So to keep the value you've toEnableViewState property to true
Session on the other hand is used when you wish to move from page to page, to keep some specific value for all the pages. For example: one keeps UserId in session so he can visit all the page which need some kind ofauthorization or authentication
Update
As you've changed you question while I was type:
In that case
Sessions is for specific time whereas Viewstate does not as Viewstate is a temporary storage mechanism. Controls that use viewstate have their state rendered into the html page as hidden input.
Hope this will help you in any way, and don't worry about vote down you'll get use to of it
If the user opens several instances of the application in different tabs of the browser, the data stored in Session will be shared by all of them (unless something special is done to avoid that). One instance modifying a value in a Session variable will overwrite the same variable saved by the other instances, causing a mixup of the data. Using ViewState ensures that each instance is not affected by the others.

Best practice for persisting User State in special kind of Asp.Net Mvc application

I will try to explain my situation and what I wanted to do. There is not any difficult and rare situation, but I can't find any relative questions or articles in internet.
I have created a web application on ASP.NET MVC 5. Users are not going to enter my application directly. Users will enter let's say to CentralInformationSystem.com. Then they must login to this website one of supported ways. After signing in, they will see a list of applications. There will be applications which has been allowed to use for the signed user. One of this applications will be my application which has developed in Asp.Net MVC.
And the main point is that our applications will not be opened in other tabs or in current tab and so on. Our application will be opened in a big iframe inside the current tab.
And other main point is our applications and CentralInformationSystem.com belong to other domains.
The other question of course is, how then I can now which user has signed in? And the answer is, CentralInformationSystem.com sends encrypted data with the query string to our web site. For example, the URL will look like that:
MyMvcApplication/Home/Index?Token=jkndid758adsai==qwdbqwiudhqwadoqidwqq=wqdiqw
Also keep in mind that they will always sent different tokens.
And after that, I will decrypt token and find to which user it belongs. Also keep in mind that, one Token can be used only once.
1. What type of application is my application?
User will enter very big form. It can actually take almost 3-4 hours. So, I have tried some-type of wizard logic. After entering some portion of datas, I will insert them to the database, get identifier from the database and store it somewhere and take the user to the next level and so on.
2. What I want to achieve?
I want to create such logic that, some identifier variables values must be stored in such place that never must be expired till the user closes browser or signing out. I don't want to increase session timeout to 5-6 hours.
3. What if user opens my application in more than one tab?
Alongside 2 I have also one problem, that user can open my website inside iframe more than one tab. I know that, in Asp.net we can differ session per each tab. But, I don't want to store datas in session, because user can stop filling forms after 20 minutes or 4 hours. Also, I cannot use cookie, because cookies will be same for all tabs.
My other option is, to inject hidden inputs with encrypted value to all views. But, I can't find how to automatically add these datas to each views. Also, it doesn't seem to me as most efficient way.
The other logic is to prevent user to open same application in more than one tab with differen tokens. But, don't how to achieve this also.
Additional:
I have read almost all articles and questions/answers. I know how to make it work. But, I want the best approach. Neither of my approaches are efficient.
Use your own concept of a persistent session that is identified by a hidden input on the page and does not expire, or at least does not expire for a very long time. Have all of your controllers derive from a single base controller and use the OnActionExecuted to add the session "key" to the ViewBag when the result is a ViewResult (you won't need it for partial views or JSON, etc). Every page can then access the ViewBag and create the hidden input - probably you want to use a partial view for this and simply include the partial on every page. Store the data associated with this session in the database.

Can you assign objects to Session in the ASP.NET C# Page_Unload method?

I am creating an ASP.NET application (using C# as the server scripting language), and need to use Session to retain data between postbacks. I am using an UpdatePanel and will have lists of textboxes etc. which are changed on the fly. These lists will be global to the code behind class. When the page posts back I will need to save the changes to these lists (and other global class variables) and so will need to save them to session. I know that lists are stored in memory and so don't actually need to be stored in session, but please ignore this fact; I am just testing the idea :P. Can it be done, and is it good programming practice if it can, to write everything to Session in the Page_Unload(object sender, EventArgs e) method of the code behind?
According to MSDN -
The Unload event is raised after the page has been fully rendered,
sent to the client, and is ready to be discarded.
As such I can see no good reason for you to be using it to store values in the Session. A more appropriate place to save the session is in the event that handles the changes to the controls in question (i.e. the text boxes you refer to).
This also keeps your code methods more focused on their responsibilities. For example if you want to save the value of a particular text box in the OnChange event, save it's value to the session in that event. Another option is of course to perform all of this in a Button Click (e.g. Save) event on post back.

Post data to different ASP.NET WebForm

In my ASP.NET WebForms application, I have a WebForm that contains an UpdatePanel and multiple views used for a wizard like interface.
At the end of the wizard, the user has an option of moving to another page by clicking a button. This new web page needs about 5 values from controls in the previous page.
What is the simplest way to do this? (Edit: ONLY using an HTTP POST with data - this is a requirement as I would use database/session otherwise)
I tried using cross-page posting with no luck, possibly because of my update panel and multiple views?
I tried using Server.Transfer, but this also breaks because of the update panel.
Important:
Data has to be sent via HTTP POST - The data can't be stored anywhere
The scenario can't be changed. I can't put everything on the same page
The simplest way to do this is by putting those values in the session object.
You could make a class that describes the data that you need to display on the redirected page. Instatiate a new instance of that at the time the user is filling out the wizard data, populate the new classes' object with the information you need, then add it to the session in the button_Click event before page redirection. On the page you are redirected to, grab the Session object, put it into a variable and extract the data you need.
I recommend you combine all the relevant pages into one; hiding panels that are not in play. ASP.NET will maintain the values of all the controls for you from post to post. The Viewstate was designed for sceneries like you describe. To keep to Viewstate size to a minimum, make sure you fill lookup values for drop-down controls in their "Init" methods.
You don't want to use the session state. The last thing you want is for the users to loose their data from previous pages because they took too long to answer.
If they're moving to another page in the solution, you have a few options.
ViewState - The ViewState is sent with the page delivery. It resides in the HTML, but is encrypted so no one can see the information. Depending on the size of the information, your page size could get rather large.
Session - This puts the information client-side via cookies.
Query String - Using the URI. This should only be used if it's non-sensitive information and if you don't want a user to be able to link back to the same action again.

Which is a better Option? - Local variables or store variables in Viewstate for a Webcontrol

Which option is better from Best practices point of view and from performance point of view?
What do you need?
a variable that's alive from the moment the ASPX page gets created and starts its lifecycle and that will be disposed with the page instance once the HTML is rendered back to the client?
or a variable that will "survive" postbacks and be sent back to the client with the HTML and come back to the server the next time the page is requested??
For option #1, you're fine and should definitely use a normal variable inside your page class - no need for ViewState.
If you need option #2 - variable value needs to be saved across postbacks and come back with the next request - then there's only ViewState as an option - storing it in a local variable in your page class won't do.
Marc
Clearly local variables is a better option. They only exist while the method is running, and they are created on the stack so they are very cheap.
The ViewState is serialised and sent to the browser in a hidden field in the response, and returned to the server in the form data in the request. That is totally unneccesary if you don't need to persist the value.
(If you do need to persist the value, ViewState is the only option of the two. Local variables are of course not persisted from one request to the next.)
Another option if you need to persist variables is to let the containing page do it for you. Create an event on the user control that fires when your variables need populating then your page handles that event.
You can get the best of both worlds in this way.
local variable : is persist for a life cycle of a single ASPX page
View state : the technique used by an ASP.NET Web page to persist changes to the state of a Web Form across postbacks.
So based on the requirement you want to choose view state and local variable .

Categories

Resources