Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET variable scope

im really new to ASP.Net and still havnt got my head round most of the concepts, im really having problems with variable, when creating a desktop application, any variable created in code for example

int n = 10;

this variable will be there until the program is running right. but in asp iv created variables which are supposed to last until the user gets of that page, so for example say i have a page which takes the users value ( call this variable n say the user type in 10) and every time the user presses the next button the code add 10 to this value. so the first time the user presses the next button

n= n + 10;

what i have found is no matter how many times i press the next button n will always equal 20, because the previous value is not saved !!

these values are populated the first time the user enters that page, once the user clicks the next button the content of these values disappear! how can stop this from happening ??

hope this makes sense !!

thanks

like image 833
c11ada Avatar asked Dec 30 '22 01:12

c11ada


2 Answers

Every time you refresh page (click also refreshes page) new instance of Page class is created. This means that all your fields become empty.

You can try to use ViewState to persist data between refreshes. But you should be care as this will increase page size. So best practice is to minimaze data in view state.

Another options is SessionState, but in this case you will keep data even between pages.

Hope this helps.

like image 144
Mike Chaliy Avatar answered Jan 12 '23 10:01

Mike Chaliy


Each time the user requests the page, it receives the request, is initialized, processed, and then rendered (read about the Asp.Net Page Life Cycle here.). So, on each page request, your variables are being created, initialized, and then assigned your values - each page load is a new life cycle. If you want values to persist betwen page life cycles, then you need to use one of the available methods (ViewState, Session, QueryString, Post, ....) to pass the values to the "next" request.

like image 32
dugas Avatar answered Jan 12 '23 11:01

dugas