Thursday, 26 September 2013

Concept of Postback in .Net

Today I will introduce you to the concept of PostBack in ASP.NET. PostBack is the name given to the process of submitting an ASP.NET page to the server for processing . PostBack is done if certain credentials of the page are to be checked against a database (such as verification of username and password). This is something that a client machine is not able to accomplish and thus these details have to be ‘posted back’ to the server.

A simple example to illustrate the usage of PostBack is a login page. After the user has typed his username and password, he clicks on the ‘Login’ button. Upon the click, the page is sent to the server to check against the database/XML file to check if the user with supplied details is an authenticated user.Then there arise certain events ( Listbox Index Changed,RadioButton Checked etc..) in an ASP.NET page upon which a PostBack might be needed. 

Suppose a case is there , If we have two dropdown lists .One dropdown list is there to select the country of the user and the other is there for his/her state/province.
Now we need to bind the second dropdown on click of an item from the first dropdown of country. This can be easily done using the concept of postback. We can set the autopostback property of dropdown to true and on click of an item of it , request will be made to the server. The autopost-back property can be selected from the properties list as shown in the screenshot below :


Also postback control is really helpful in case if we need to do some tasks on our page for the very first time it gets loaded. For e.g. If I need to display date on my web page and I do not want it to get refreshed with every postback (say if I click on Submit button and I do not want my Date to be refreshed) then I can use postback.



IsPostBack is a Boolean property of a page which is set (=true) when a page is first loaded. Thus, the first time that the page loads the IsPostBack flag is false and for subsequent PostBacks, it is true. An important point to be noted here is that each time a PostBack occurs, the entire page including the Page_Load is ‘posted back‘ and executed. Thus a very common programming practice is that whenever some part of the code is to be executed just the first time a page loads, it is checked against the IsPostBack flag as is done in the screenshot above. If you have not understood the concept clearly, do not worry. Programming examples in subsequent posts will help making this concept clear.

Happy Coding!

No comments:

Post a Comment