|

Introduction
This article explains the correct usage of the IsPostBack checking in Asp.Net.
Using the code
The Presence of an if(!IsPostBack) code block in any Asp.Net C# article or book chapter is as common as a bird on a tree branch. But a proper explanation about its usage is as rare as an unicorn. This short article tries to address this issue.
When an aspx page is displayed for the first time, any code within the Page_Load event, including the if(!IsPostBack) is executed. When the same page is displayed in subsequent times, only the code outside the if(!IsPostBack) is executed. The second scenario happens when there is, say a button_click event, which reads some values either from a server control or a local variable of the page and displays the same page with these values.
The enclosed demo project has a Dropdown List box named lstCity and a local boolean variable named whetherIsGood. The Dropdown list box has three possible cities as items – Houston, Dallas and Austin. The Page_Load event sets the SelectedIndex of the listbox to Dallas (by assigning a value of 1) and the whetherIsGood variable to true. This could be done in three different possible ways as shown below. When the button “Set” is clicked it shows the selected item from the list box and the variable value in two text boxes.
Code1:private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
lstCity.SelectedIndex = 1;
whetherIsGood = true;
}
}
Code 2:private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
lstCity.SelectedIndex = 1;
}
whetherIsGood = true;
}
Code 3:private void Page_Load(object sender, System.EventArgs e)
{
lstCity.SelectedIndex = 1;
whetherIsGood = true;
}
As explained within the code comments, Code 2 has the expected behavior. So put the code which sets parameters to a server control within the if(!IsPostBack) code block, and put any code which sets a local variable outside this block, unless you are using a static variable.
Points of Interest
You could find a related article at MSDN.
| You must Sign In to use this message board. |
|
| | Msgs 1 to 10 of 10 (Total in Forum: 10) (Refresh) | FirstPrevNext |
|
 |
|
|
I never thought IsPostBack requires explanations? It's a property and if you understand the basics of object oriented programming AND web development you would figure out what it does by it's name. Much more interesting would be to explain what and when happens when a page is loaded - then you would get real understanding of the flow: for example what which method gets called first : the postback event handler or page_load, also if you put a code in your aspx page using <% ... %> block will page_load execute before or after that block. What about the Page.Unload event and whatfor can one use it. I would recommend you to write an article about these stuff - they aren't so self-explanatory and obvious.
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
Nsimeonov,
Thanks for your comments. The purpose of the article was mainly to explain which type of code goes within the IsPostBack block, and which remains outside of it. I have seen few programmers, in a hurry, put all the code within this if block and wonder why a particular variable was not initialized. The idea of this article was to save some time in debugging, even it happens to be only a couple of minutes
ThirstyMind
|
| Sign In·View Thread·PermaLink | 5.00/5 (1 vote) |
|
|
|
 |
|
|
You cannot save people from their own stupidity or stop them to work while they are tired. However a better understanding what goes on when a user requests a page or clicks a button on it would help much more people than explaining something that's self explanatory and only newbies with less than 2 months experience can get confused of.
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
 |
|
|
 |
|
|
Actually I had a problem the other way around. I'm new to .Net (but not to Web development) I asked once if IsPostBack was the same as Request.HttpMethod.Equals("POST") and it seems it is.
I keep wondering why the heck .Net will preserve some values, such as objects or content generated as a result of some process triggered by a POST submition (e.g. user authentication), even if I did a new GET request (i.e. go to address bar and hit enter), that's definitely not the way HTTP works.
The very last comment, (unless you are using a static variable , in its context) gives me more info than the rest of the article, though I'm still not sure what's this "smart cache" about —I really hate when M$ gets creative and helps me.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
>> I asked once if IsPostBack was the same as Request.HttpMethod.Equals("POST") and it seems it is. <<
No it isn't. HttpMethod may be GET or POST. POST when data was submitted TO this page (not necessarily FROM the same page - the origin may be another page as well).
IsPostBack had nothing to do with the HttpMethod - it indicates whether the page is loaded for first time or a control initiated a postback (a dropdown list was changed, a button was clicked, a DataGrid should display another page from the bound dataset etc.)
And about the article - your question was right in the bullseye and my comments are more informative than the entire article explaining something that's so self-explanatory I just can't imagine how it would ever need additional explanations except for people not speaking english so you have to translate to different languages - that would be more helpful IMO.
Regards, Nikolay
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
IsPostBack had nothing to do with the HttpMethod - it indicates whether the page is loaded for first time or a control initiated a postback (a dropdown list was changed, a button was clicked, a DataGrid should display another page from the bound dataset etc.)
I really haven't checked much, but as I've seen so far .Net uses POST as the default method for the updates (whatever event you mentioned before, or other), they even seem to call a DoPostBack() (or whatever) javascript function to send the event to the control —after all, the event occurs on the client and it's supposed to be handled in the server (and there's even people who don't understand even that because of how .Net works).
I've seen some kind of hash code in the pages (as a hidden field), so I think .Net could distinguish what page is invoking the POST method, but even if that's how they do it, it can be emulated (and so the Referrer), so there's no secure way to know if you're being called from one page or another.
And about the article - your question was right in the bullseye and my comments are more informative than the entire article explaining something that's so self-explanatory I just can't imagine how it would ever need additional explanations except for people not speaking english so you have to translate to different languages - that would be more helpful IMO.
As I see myself on this conversation, I think most of cases the questions will be about .Net concepts (since it's somehow of an emulator of desktop (windows) applications for the web , something that may be not that simple to swallow for those that have been working on the web for a while and haven't touched .Net for development)
Anyway, the thing is I still don't quite get some of .Net behaviors, nor the reason of their existence (that darn smart cache is one of them). But then again, I've had troubles trying to understand M$ IE since I've working on standard-compliant web development.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
It isn't about security, it is about page initialization and what actions you are supposed to perform - do you have to initialize some objects or they are already in tact. You may have <form action="SomeOtherPage.aspx"><input type="submit" value="click me"></form> and clicking the button will open "SomeOtherPage.aspx" and HttpMethod will indicate a POST not a GET, however IsPostBack wouldn't be true.
The "hash" code you are referring is actually the hidden field __VIEWSTATE containing the values for all controls with property EnableViewState set to "true". So be careful (this is the default setting as well): If you want to be able to trigger "OnChange" event for textboxes or dropdownlists - leave it true, if not - you better set it to false and not waste bandwidth. DataGrids use ViewState heavily and add way too much overhead so if you can update the grid on every page load it would be better IMO.
>> since it's somehow of an emulator of desktop (windows) applications for the web <<
Oh man... oh man... How long did you work with asp.net, honestly, because what I read shows me that you don't understanding a single thing about how ASP.NET works and what it really is. This is one of the most ignorant and uniformed statements I've ever read recently... no joke. I know I wrote some stupid things on and off but saying that ASP.NET is somohow of an emulator of a desktop application for the web - now this deserves an award!
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
It isn't about security, it is about page initialization and what actions you are supposed to perform - do you have to initialize some objects or they are already in tact. You may have <form action="SomeOtherPage.aspx"><input type="submit" value="click me"></form> and clicking the button will open "SomeOtherPage.aspx" and HttpMethod will indicate a POST not a GET, however IsPostBack wouldn't be true
I never said it was about security (though it is related, that's a different topic), I said you have no secure way to know which page you came from.
Back to topic, I suppose the way .Net knows if the page is a post back or not is if the controls are already loaded in memory or not (which seems to be a waste for me, but then again, I don't work for/with M$). The example you give me is interesting, I'll test it later, thank you.
The "hash" code you are referring is actually the hidden field __VIEWSTATE containing the values for all controls with property EnableViewState set to "true". So be careful (this is the default setting as well): If you want to be able to trigger "OnChange" event for textboxes or dropdownlists - leave it true, if not - you better set it to false and not waste bandwidth. DataGrids use ViewState heavily and add way too much overhead so if you can update the grid on every page load it would be better IMO.
Now, this is interesting. So, if I get you right this would be why some controls preserve a given status, as I asked before, right? Mhh... that deserves some tests (though they'll likely have to wait until Monday)
Oh man... oh man... How long did you work with asp.net, honestly, because what I read shows me that you don't understanding a single thing about how ASP.NET works and what it really is. This is one of the most ignorant and uniformed statements I've ever read recently... no joke. I know I wrote some stupid things on and off but saying that ASP.NET is somohow of an emulator of a desktop application for the web - now this deserves an award!
How much have I worked with Asp.Net? I thought I've already said I'm new to it, but I've been working on web projects some time now.
As for what is .Net, eto... a framework? That has nothing to do with it being a desktop application emulator for the web , since it can be both (and even a good one). I mean, if you understand that HTTP is an asynchronous/stateless client/server connection, then you do understand that preserving control states from one page to another (without me, the programmer, actually coding it) looks just like a desktop application emulation, right?. Anyway, that's just how I see Asp.Net thus far (I just asked someone who's been working with .Net for some years, and he agrees —although that weren't his exact words).
The award... is it an AlienWare? Maybe an iPod? I hope it's worth it!
|
| Sign In·View Thread·PermaLink | 5.00/5 (1 vote) |
|
|
|
 |
|
|
General News Question Answer Joke Rant Admin
|