How postback works in ASP.NET

转载 2007年09月18日 15:39:00

这篇文章分析了asp.net页的postback机制, 并在后面用js脚本模拟了一次单击按钮postback的事件


How postback works in ASP.NET

In this article, we will take a closer look at how ASP.NET pages post back to themselves, and how to customize this feature in our web applications.

Published: Dec 10, 2002 | Last Edited: Aug 20, 2005
Tested with: ASP.NET 1.1
Category: ASP.NET

<script type="text/javascript"> <!-- google_ad_client = "pub-3480949677475568"; google_ad_width = 468; google_ad_height = 15; google_ad_format = "468x15_0ads_al"; //2007-03-30: Article Page Top Links google_ad_channel = "3741709143"; google_color_border = "FFFFFF"; google_color_bg = "FFFFFF"; google_color_link = "0000FF"; google_color_text = "000000"; google_color_url = "008000"; //--> </script> <script src="" type="text/javascript"></script>
<iframe name="google_ads_frame" marginwidth="0" marginheight="0" src=";dt=1190100578859&amp;lmt=1190100578&amp;format=468x15_0ads_al&amp;output=html&amp;correlator=1190100578812&amp;channel=3741709143&amp;;color_bg=FFFFFF&amp;color_text=000000&amp;color_link=0000FF&amp;color_url=008000&amp;color_border=FFFFFF&amp;;cc=100&amp;ga_vid=703784493.1190100579&amp;ga_sid=1190100579&amp;ga_hid=2081970980&amp;flash=9&amp;u_h=1024&amp;u_w=1280&amp;u_ah=996&amp;u_aw=1280&amp;u_cd=32&amp;u_tz=480&amp;u_his=2&amp;u_java=true" frameborder="0" width="468" scrolling="no" height="15" allowtransparency="allowtransparency"></iframe>


In this article, we will take a closer look at how ASP.NET pages post back to themselves, and how to customize this feature in our web applications.

function __doPostBack(eventTarget, eventArgument)

One of the most important features of the ASP.NET environment is the ability to declare controls that run on the server, and post back to the same page. Remember the days of classic ASP? We would create a form which would accept the user's input, and then we would most probably have to create another page that would accept all those inputs, either through HTTP GET or POST, and perform some kind of validation, display and action. Sometimes, even a third page was necessary to perform our actions. This wasted a lot of time and complicated things when you had to make a change. But of course, this is not necessary any more with ASP.NET. There is no need to create second pages that accept the inputs of the first, process them and so on. Form fields and other controls can be declared to run on the server, and the server simply posts the page back to itself and performs all the validation, display and actions. Our life as web developers has become a million times better. But how exactly is this done?

When a control is declared to run on the server, a VIEWSTATE is created which remembers the ID of that control, and the method to call when an action is performed. For example, let's say we input this HTML on a page:

1 <script language="VB" runat="server">
2 Sub Test_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
3     'enter your code to perform
4 End Sub
5 </script>
6 <html>
7 <body>
8     <form runat="server" id="myForm">
9         <asp:linkbutton id="Test" runat="server" text="Create Text file" onclick="Test_Click" />
10     </form>
11 </body>
12 </html>

This is a very simple page. We declare only one web control, a linkbutton, to run on the server, with an ID of Test and we assign a method called Test_Click to run when the link is clicked on the page. The linkbutton has to be wrapped inside a form that runs on the server as well. We save the above as an ASPX page and then we browse to it. The HTML that gets created looks like this:

1 <html>
2 <body>
3     <form name="myForm" method="post" action="test.aspx" id="myForm">
4         <input type="hidden" name="__EVENTTARGET" value="" />
5         <input type="hidden" name="__EVENTARGUMENT" value="" />
6         <input type="hidden" name="__VIEWSTATE"
7         value="dDwtMTAwOTA0ODU1NTs7PsllCK1DzvZsK0J6OQ2dxKqmEwVs" />
9 <script language="javascript">
10 <!--
11 function __doPostBack(eventTarget, eventArgument) {
12     var theform = document.myForm;
13     theform.__EVENTTARGET.value = eventTarget;
14     theform.__EVENTARGUMENT.value = eventArgument;
15     theform.submit();
16 }
17 // -->
18 </script>
20 <a id="Test" href="javascript:__doPostBack('Test','')">Create Text file</a>
21 </form>
22 </body>
23 </html>

Our link calls the javascript function __doPostBack when clicked (that's 2 underscore symbols in front of it). You do not write this function, instead it is generated by the ASP.NET engine and automatically included in our page. It submits the form to the same page, and accepts 2 arguments:

  1. eventTarget: the control doing the submission
  2. eventArgument: any additional information for the event

For example, our generated link button, is telling the javascript function that the control submitting the form is the one with ID=Test, and no further information is needed for the second argument. The javascript function is actually setting 2 hidden form fields with these 2 arguments: __EVENTTARGET and __EVENTARGUMENT. When the form is submitted back to the server, the server reads these 2 hidden form fields and decides what submitted the form and performs the necessary action. In this case, the server will determine that the linkbutton performed the action, and will execute the Test_Click method.

Lastly, I should point out that at least one control needs to be set to Visible, for the server to generate the __doPostBack function in our page. Even if we have numerous web controls declared to run on the server, but they are all set to Visible=false, then the javascript function will not be included and we will not be able to perform any actions. You can test this out, by changing the linkbutton source code to this and looking at the source code generated when it runs:

1 ...
2 <asp:linkbutton id="Test" runat="server" text="Create Text file" onclick="Test_Click" visible="false" />
3 ...

Calling __doPostBack in our own javascript

So now that we have seen how the postback process works, we can easily create web applications to use this feature. Let's go through an example, and hopefully things will clear up more.

Let's assume that we have a link on our page that creates a file on the server. When we click on the link, we might want to pop up a javascript input box where the user can type the filename. If the user types something in and then clicks OK, the page will post back to itself and perform the action. If the user clicks on CANCEL, then nothing will happen. Something like this:

User Prompt

Let's see the HTML code needed to do this:

1 <script language="VB" runat="server">
2 Sub CreateFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
3     Dim strFileName As String = funcParam.Value
4     'custom code to create a text file
5 End Sub
6 </script>
7 <html>
8 <head>
9 <script language="JavaScript">
10 //ask for user input and then create file
11 function CreateFile() {
12     //get filename from the user
13     var fileName = prompt('Type the name of the file you want to create:','');
14     //if the user clicks on OK and if they have entered something
15     if ((fileName) && (fileName!="")) {
16         //save the filename to the hidden form field 'funcParam'
17         document.forms['myForm'].elements['funcParam'].value = fileName;
18         //call the postback function with the right ID
19         __doPostBack('CreateFile','');
20     }
21 }
22 </script>
23 </head>
25 <body>
26 <form runat="server" id="myForm">
27     <a href="javascript:CreateFile();">Create Text file</a>
28     <asp:linkbutton id="CreateFile" runat="server" onclick="CreateFile_Click" />
29     <input type="hidden" runat="server" id="funcParam">
30 </form>
31 </body>
32 </html>

Inside our form we have 3 controls:

  1. a link to call the javascript CreateFile function.
  2. a linkbutton that runs on the server, with ID CreateFile, and a CreateFile_Click method which runs when it is clicked.
  3. a hidden form field with ID funcParam, to store the filename that the user types in our javascript pop up.

Our custom javascript is very simple. First, it pops up an input box, where the user is asked to type a filename. If the user clicks on OK, and actually enters something, then we store this filename in our hidden form field, funcParam. Then we call the __doPostBack function, making sure we pass the ID of the linkbutton to make it think that it's the linkbutton control that is submitting the form.

Since the linkbutton has an event called CreateFile_Click which runs on the server when it is clicked, then the page will submit to itself, and this method will run. The first thing we want to do in this method is get the name of the filename, and this is done by funcParam.Value. The remaining code to create the actual file on the server is not included, since the purpose of this article is not to show this. You can add it in, or create some other code here that performs a different action.

Keep in mind that for every javascript function that you create which calls the __doPostBack function, you will need to create a control that runs on the server - just like the  shown above. We are not restricted to linkbuttons though - we can use any of the ASP.NET web controls.


We have seen how the postback function works with ASP.NET, and how to use it in our web applications. This article has concentrated on how to use this with a simple prompt box, but you can use a similar technique to combine the __doPostBack function with a showModalDialog function, or to return a value from another pop up window.


How Tomcat Works -- 目录

《How Tomcat Works》这本书的读书笔记,及主要内容感想。 作为一个世界范围广泛使用的强大框架,Tomcat必然有非常多的设计思想、设计模式,让我们学习。 不看这种包含设计思想的框架,只...
  • puma_dong
  • puma_dong
  • 2015年12月08日 00:38
  • 1592

《how tomcat works》翻译开篇

《how tomcat work》翻译此书只为学习,有错误,不到位之处,请指出。文笔欠佳,请多海涵。简介概述欢迎来到《how tomcat works》,这本书剖析了当下免费的 ,开源的,并且是最为流...
  • tomcat_how_work
  • tomcat_how_work
  • 2015年11月01日 23:26
  • 726

探索《How Tomcat Works》心得(一)

很久之前就开始对Tomcat感兴趣,于是开始查询如何学习Tomcat,发现论坛里好多的观点都说,《How Tomcat Works》是学习Tomcat的必备书籍。于是自己开始学习这本书。看这本书到现在...
  • u012561308
  • u012561308
  • 2016年05月02日 11:01
  • 687


浅谈ASP.NET的Postback 说道ASP.NET的Postback,就得说Web Page的生命周期,但是Web Page的生命周期却不是三言两语就能够说得清楚的,所以在这里单纯站的编...
  • songjianyue12345
  • songjianyue12345
  • 2016年11月28日 15:35
  • 842


这本书之前就看过,然而也就开了个头就废弃了,所以一直耿耿于怀。这次决定重新开始,在此记录一些学习心得和本书的主要知识点。所有代码也将托管在GitHub上面。O(∩_∩)O 本章节,简要介绍HTTP协议...
  • laiwenqiang
  • laiwenqiang
  • 2017年05月16日 16:10
  • 655

how tomcat works 总结

希望各位网友在看完>一书或者鄙人的tomcat专栏文章后再看这篇博客 这里主要是梳理各个章节的核心概念 第一章 一个简单的Web服务器 第1章从这本书一开始就介绍了一个简单的HTTP服务器。要建立一...
  • dlf123321
  • dlf123321
  • 2014年11月02日 20:46
  • 1546

《how tomcat works》书籍下载

  • gjf281
  • gjf281
  • 2014年05月18日 23:19
  • 632

how tomcat works 读书笔记(一)----------一个简单的web服务器

http协议 若是两个人能正常的说话交流,那么他们间必定有一套统一的语言规则 http分两部分,一个是请求(客户端发给服务器),一个是回复(服务器发给客户端)。 先看http请求  下面就是一个htt...
  • dlf123321
  • dlf123321
  • 2014年10月14日 10:50
  • 2056

推荐一本好书《How Tomcat Works》

  • wangchengsi
  • wangchengsi
  • 2009年03月03日 07:09
  • 31517


1概述 从认知科学中我们知道大脑在面对一个复杂事物时,会自动对事物进行归纳分组,降低认知难度。对于复杂的OS系统,一个人穷其一生也难以掌握全部细节,故为了理解一个系统,我们需要一定的抽象,从整体对系...
  • looiezheng
  • looiezheng
  • 2017年12月18日 22:37
  • 34
您举报文章:How postback works in ASP.NET