-4

I have something like

protected void Page_Load(object sender, EventArgs e){
 country.Text = "USA";
}
protected void Button_Click(object sender, EventArgs e){
 Console.Write(country.Text);
}

and when the user clicks on the button, it always prints "USA", even if they wrote something else in the country TextBox, it means that Page_Load() gets fired each time a button (or any other event, I guess) is clicked.
I know how to fix this, by looking at this question, but why does that happen?

AlessandroF
  • 542
  • 5
  • 16
  • How would you expect a server to respond with a page if it doesn't? Maybe take a look in your browser developer tools network tab to see what is happening when you click that button... – Caius Jard Oct 22 '20 at 09:06
  • I expected that the page didn't entirely reload, but only the actions in "Button_Click" get fired. – AlessandroF Oct 22 '20 at 09:10
  • 3
    I think there's a fundamental flaw in your understanding of web forms that needs addressing – Caius Jard Oct 22 '20 at 09:17
  • 2
    `if (!IsPostBack) { country.Text = "USA"; }` And Page_load is always fired (PostBack included). https://www.c-sharpcorner.com/UploadFile/8911c4/page-life-cycle-with-examples-in-Asp-Net/ – VDWWD Oct 22 '20 at 10:10
  • Page_Load fires *because the page is loading*. Interactions with UI elements in Web Forms often cause a postback, which is an HTTP POST request back to the page. Thus the page is loading again. By the way - why are you learning Web Forms in 2020? It's a dying/dead framework. – mason Oct 22 '20 at 13:00
  • Because I work in a software house that uses ASP.net & web forms – AlessandroF Oct 22 '20 at 15:24
  • See my post below. I explain the concent of a "round trip" this is a MUST grasp concept. So anytime a button, dropdown list etc. is changed (and it set to post back), then the whole page is sent up to the server - and page load will run every time. So that's why ANY setup code in page load is fine, but that setup code has to be placed in a if/then block that checks for postback = false (this means only run your setup code one time, and the first time on the first page load which is NOT considered a post back. This basic concept of round tripping is the Rosetta stone of how web pages work. – Albert D. Kallal Oct 22 '20 at 19:14
  • 1
    To be fair, there likely should have been a event called FirstPage load. And for the large numbers of people who come from desktop development? The page load only fires one time on page load - so there is ZERO surprise that many would assume a same or similar event mode for web forms. I wish someone had taken just 4 minutes out of their life to explain this to me. Having authored and being involved in 3 books, attended university (computing science). I was first surprised by this event model at first. Any comments here centered around "duh" what you expect to happen are simply un-kind. – Albert D. Kallal Oct 22 '20 at 19:27

2 Answers2

1

The web page is sitting on the client side web browser. When you click a button, the whole page is sent up to the server. Now you code behind can not only run, but modify controls, and does whatever you want. Once all that code is run, then the browser page is sent back down to the client.

I have often suggested that a FirstPage load event would have helped mountains here. However, over time, I think the page load having to fire each time is fine, and that the setup actually helps and promotes the fact that it runs every time. However, in desktop development - from VB6, .net, heck even delphi and C++ desktop forms? The page load even ONLY ever fires one time. So yes, it is surprise to many that web forms don't work this way. The bottom line is that page load fires every time, and the simple matter is a WHOLE NEW fresh page is sent up to the sever EVERY TIME. So, while there could have been two events, often quite a bit of page load code has to run in both cases. So then having two seperate events would cause just as much trouble.

So for code that runs first time (such as setting up the text box value)? Well, if you need that code to run each time (and you might!!!), then you place it outside of the if/then block that checks for the IsPostback. So for code to setup things such as defaults - yes, you need that code inside your IsPostBack = false block.

Web pages are what we call state-less. They are sitting on the users desktop. There is NO LIVE connection to the server. The user can close that web browser or turn off their computer. And when the user closes the browser - no information or talking is sent to the server. So you can have 2 or 2000 users typeing or editing in their brwoser - the web server does not care, see or even know that users are doing things. And the web server considers them NOT CONNECTED. They are just a web page - that page can be closed - the server does not even know the user closed the web site (there is no web page close event like desktop software). So the whole design of web pages are sate-less - and disconnneced. The web server does not know if that web page is still open, being used, or been closed. The ONLY time the web server can do ANYTHING is if you send the page back up to the server. At that point EVERYTHING in that web page starts over from scratch every post back (hence the term state-less). However, thankfully things like a text box have what is called a "view state" and they DO survive those round trips. If a control does not have a view state, then they also would lose their values on each post back. One VERY nice feature of webforms is most controls have the ability to keep their viewstate (that just means the value(s) of such controls can survive a round trip.

So when you click a button, then a whole page postback has to occur, since any code running behind would not be able to look at/ see / change the value of controls on the form. In fact, we often seen someone say run a ajax web method (in the same page) and then wonder why their code behind (in that web method) can't change controls. In fact you can write code to change controls, but it only changing the server side copy, and the copy sitting on the user's desktop is not changed. In fact, when they do (eventually) a post back, anything the code behind changed is lost.

So when you click on a button, the page load event will run FIRST and then your button code. This is how it works.

So 99% of the time, when I start typing and writing code in page load?

You do this: (say to load up a datagrid with a data table).

if IsPostBack = False then
   GridView1.Datasource = myrst("SELECT * from tblhotels")
   GridView1.Databind()
End if

So, you have to "assume" and "write" code that means the page load event fires every time. However, in above, we only want the first time setup code (to load up a gridview) to run one time - the first time the page loads. So now, you might have 5-6 buttons on the page, and the above code in the page load will not run since we check/test if this is a post back.

So the whole web page has to travel up to the server, else your code behind can't modify any controls or values on the web page. Once that code runs, then the page travels back down to the client side and is again just sitting on the users desktop. So clicking a button HAS to send the whole web page back to the server, else the values of controls on the web page could not be modified, and worse the results of that code would never be displayed back in the browser. So code behind can't JUST modify one control. it needs a whole copy fo the web page first, and then you can change a control (or several) and then the whole page makes the trip back to the browser. So you can't write code to JUST change one control without first having a WHOLE copy of the web page with everything. However, you can use what is called a update panel. This will allow you to run code that updates JUST part of the page. However, even in that case, the page post back event does run first - this is often called a partial page post back. So you can drop in a update panel, and have buttons and code in that update panel - they can only modify things inside of that update panel, but you note that the whole page does not replot or re-fresh. You can also hand code JavaScript ajax calls, and they can client side modify some controls (and even call routines server side). But you still have to assume that code behind can NOT see + use those controls until such time the web page travels up to the server. This applies even when using a up-date panel (the code behind can only modify controls in the update panel). Update panels are very nice in that you don't have to wire up and hand code a whole bunch of ajax and JavaScript to allow partial updates of the web page and not have to cause a full page post back. But as noted, even when using a up-date panel, the page load event does fire. So for the most part, you in general write the page load and setup code inside of that postback=false code block.

Albert D. Kallal
  • 42,205
  • 3
  • 34
  • 51
-1

This is what the ASP.Net Button class tells us about the Button class:

By default, a Button control is a Submit button. A Submit button does not have a command name (specified by the CommandName property) associated with the button and simply posts the Web page back to the server.You can provide an event handler for the Click event to programmatically control the actions performed when the Submit button is clicked.

ManojRawat
  • 61
  • 1
  • 8
  • 1
    The problem is not the button but the Page Life Cycle when loading a page and/or doing a PostBack. – VDWWD Oct 22 '20 at 10:11