Strange little thing called postback.
Date posted: 25/12/2013
You haven't filled in compulsory values.
The email is not correct
I guess that most people know what postback is. Well, at least most developers that have been using ASP.NET Web Forms. If so, you know that postback is an essential part of your application. In this article we are going to search in depth what postback actually is, how it is created and how it can be used in combination with other parts of web applications.
Brings back memories
Probably the first time you heard of postback was when you tried to create a DropDownList the way it is in the following example.
<asp:DropDownList runat="server" ID="DropDownListID" />
<asp:Button runat="server" Text="Click" OnClick="ButtonClicked" />
<asp:Label runat="server" ID="LabelID" />
protected void Page_Load(object sender, EventArgs e)
{
DropDownListID.Items.Add("Element 1");
DropDownListID.Items.Add("Element 2");
}
protected void ButtonClicked(object sender, EventArgs e)
{
LabelID.Text = "Selected " + DropDownListID.SelectedValue;
}
Feeling proud at how you managed to capture the DropDownList's value and print it, you might have suddenly realized that your list contained two more elements than before. Troubled, you might have probably asked some senior developer in order to get an answer; you should use the IsPostBack parameter.
if (!IsPostBack)
{
DropDownListID.Items.Add("Element 1");
DropDownListID.Items.Add("Element 2");
}
And suddenly, it worked. That's some magic here.
This may have been the first time you heard about postback. You heard that the IsPostBack is a property that is always false the first time you request a page but is true when an event causes postback, for example clicking a button. Later on you found out that there are web controls like the DropDownList you had already seen, which could be set events like OnSelectedIndexChanged so if a postback happened. they would cause certain methods to occur. There was an AutoPostBack parameter as well which could cause a postback of its own. In that way whenever you picked a new element in the list you created a postback.
Later on you found out that there exists something called viewstate and that this viewstate carried along with it all the values your server controls contained. This viewstate was sent back to the server when a postback request was created and this way the server could find out that you had either chosen Element 1 or Element 2. Because that value was automatically stored within the viewstate. That was great.
Later on you heard people arguing that this great thing called viewstate was not so great after all as it could grow that big that could slow down the request and in total the response time. Then people started disabling viewstate whenever they could do so and talking about ASP.NET MVC and using pure JavaScript to create their requests. No matter how this discussion ended, about that time there may be a day when you look at yourself at the mirror and wonder "What the heck is this postback that I've been using for so long?"
Even though only a few or none of the above may have occurred to you, we are now ready to see what is actually happening during a postback.
Postback in action
Let's create one more DropDownList control
<asp:DropDownList runat="server" ID="DropDownListID" OnSelectedIndexChanged="IndexChanged">
<asp:ListItem Text="Item 1" Value="1" />
<asp:ListItem Text="Item 2" Value="2" />
</asp:DropDownList >
This server control will be rendered into a simple select HTML code
<select name="DropDownListID" id="DropDownListID">
<option selected="selected" value="1">Item 1</option>
<option value="2">Item 2</option>
</select>
So far so good. What we are actually interested in, is the effect of the AutoPostBack parameter. Let's add AutoPostBack="true" to the control.
The new HTML code consists of some interesting staff.
<select name="DropDownListID" onchange="javascript:setTimeout('__doPostBack(\'DropDownListID\',\'\')', 0)" id="DropDownListID">
<option selected="selected" value="1">Item 1</option>
<option value="2">Item 2</option>
</select>
First thing to notice is the presence of a JavaScript call
onchange="javascript:setTimeout('__doPostBack(\'DropDownListID\',\'\')', 0)"
This command will call the __doPostBack function. If we perform some HTML decoding in the previous line, we are calling __doPostBack('DropDownListID',''). This __doPostBack function is automatically inserted in the code by the ASP.NET
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
And what it actually does is submitting the form having __EVENTTARGET.value equal to 'DropDownListID' and __EVENTARGUMENT.value equal to '', in our case.
That's all concerning the client part. Now the request is sent to the server.
To begin with, keep in mind that a postback is always caused by a POST request. However creating your own POST request code will not set IsPostBack to true.
Now, let's see what the server will do next. Request.Form, contains info sent to the server in case of a POST request. It contains a lot of stuff such as viewstate.
Two interesting parts are __EVENTTARGET and __EVENTARGUMENT which we already saw while viewing client side. You may be right to think that this info is transferred all the way to the server. __EVENTTARGET contains the ID of the control which caused the postback, while __EVENTARGUMENT contains the info it contains.
That's the way server knows which control caused the postback and is able find the proper method to call. A postback will cause the event handlers specified to the control, raised. In the example, the postback will call the IndexChanged method. This method will be set to the page life cycle position saved for controls events. That is after Page_Load and before Page_PreRender.
Let's see how we can use __EVENTTARGET and __EVENTARGUMENT to find out which control caused the postback or what the arguments are using
if (IsPostBack)
{
if (!String.IsNullOrEmpty(Request.Form["__EVENTTARGET"]))
{
string ControlID = Page.Request.Params["__EVENTTARGET"];
Control postbackControl = Page.FindControl(ControlID);
}
if (Request.Form["__EVENTARGUMENT"] != null)
{
string argumentID = Page.Request.Params["__EVENTARGUMENT"];
}
}
Knowing which control caused the postback may sometimes save time from refreshing data, in case you may not need to. Something like the next piece of code could save a few seconds of your response time.
if (!IsPostBack)
//Retrieve and compute data
;
else if (!String.IsNullOrEmpty(Request.Form["__EVENTTARGET"]))
if (Page.Request.Params["__EVENTTARGET"] != "DropDownListID")
//Retrieve and compute refreshed data
;
else
//You do not need to refresh data. Just use viewstate
;
In the example, __EVENTARGUMENT is an empty string. Other types of postback do not end up that way. Intentionally we could call the __doPostBack method ourselves and use the arguments we like.
Server controls such as Buttons may cause direct postbacks without JavaScript. For example a button may be rendered as
<input type="submit" value="Click me" name="ctl02">
Such a postback would contain no values in __EVENTTARGET or __EVENTARGUMENT.
How do we know which control caused the postback then, if __EVENTTARGET is empty?
Remember our button?
<asp:Button runat="server" Text="Click" OnClick="ButtonClicked" />
If we clicked that, the Request.Form would contain something like this ,,,&Button1=Click&,,,
This is the way to go on.
In the previous method we should add
if (!String.IsNullOrEmpty(Request.Form["__EVENTTARGET"]))
{
string ControlID = Page.Request.Params["__EVENTTARGET"];
Control postbackControl = Page.FindControl(ControlID);
}
else
foreach (string controlID in Request.Form)
{
//Check all possible info within the form
Control objControl = Page.FindControl(controlID);
if (objControl is Button)
//If it is a button, this is what you are looking for
{
string buttonControlID = objControl.ID;
break;
}
}
Finally, keep in mind that you can create your own custom controls which can create and handle postbacks the way you want.
Avoid postback if possible
Postback is usually great, but it may sometimes cause trouble. The faster a page responds the better a website feels. Even though there may be hundreds of things you could do to speed up your website you should always keep in mind that excessive use of postbacks may backfire.
Postbacks allow you to have server side control over your page but that will cause a new request to be sent and a new response to wait upon. That request will carry all the viewstate info along with it. Let alone the fact that possible client JavaScript calls will be reset.
A postback is NOT user friendly, therefore it should be used only when necessary. That means, when you need to do something which cannot be done client sided. For example a redirect can be done using a Hyperlink server control or a button. The Hyperlink will be rendered into an HTMLAnchor control and send a brand new request to the server asking for the new page and take it back. On the contrast, the button will cause a postback (carrying the viewstate info along) run through all the handlers till it reaches the button event handler and then redirect. Even better we could straight away use an HTMLAnchor control.
In order to make a part of the page disappear we could use JavaScript or make a postback and set its visible parameter to false. You should always go for the JavaScript whenever you can.
To change the data in your page, you need not cause a postback. Use AJAX instead. Keep in mind that AJAX can't be the key to the solution all the time. You should know when it is best to be used.
You may also try to reduce the total viewstate size if there are controls which do not need viewstate. You can set their EnableViewState property to false. EnableViewState is by default set to true.
Summary
Postback is an ASP.NET technique which helps us create a request carrying viewstate info back to the server, in order to create a new response. It uses client side JavaScript to submit the HTML form and will set the IsPostBack parameter to true. We can use the submitted form to get info concerning the postback. Even though postback may prove to be useful, it should be avoided when possible as it may decrease our websites speed.
Back to BlogPreviousNext