什么是PostBack(译) What is a postback?
下面的内容是针对ASP.NET新手的
PostBack什么时候被引发?
PostBack由客户端浏览器引发。通常是用户操作(点击按钮、修改下拉框等)页面中的某个控件,然后该控件发起一个PostBack。最后该控件的状态加上本页面上所有的其它控件(也就是ViewState)一起回发到服务器。
PostBack时发生了什么?
通常情况下PostBack会触发web服务器创建一个被引发了PostBack的页面page类的实例。然后这个page对象就步入了它常规的页面生命周期,与一般情况稍有差异(见下文)。如果你没有在页面的生命周期内将用户重定向到另一个指定的页面,PostBack的最终结果将是再次将相同的页面呈现给用户,然后开始等待下一个PostBack。
为什么需要PostBack?
web应用是运行在web服务器上的。为了处理用户请求所导致的应用状态的更改或是页面的跳转,你需要一些在web服务器上运行的代码。实现该目标的唯一方法就是收集用户正在使用的所有信息,然后将它们发回到服务器。
一些新手应该注意的事情
- 控件的状态在回发页的环境中是可用的。通过这些信息你可以在后台操作页面控件或是重定向到其它页面。
- WebForm里面的控件包含events(事件)、event handlers(事件处理器),页面生命周期的初始化部分将在引发PostBack的控件的后台事件被调用前执行。即当用户点击按钮时,会先执行Page Init和Load事件再执行按钮单击事件。
- 页面PostBack(回发)时,属性“Page.IsPostBack”的值为“true”,其它情况(例如页面初次载入)为“false”。
- Ajax和MVC技术修改了PostBack的工作模式。
The following is aimed at beginners to ASP.Net...
When does it happen?
A postback originates from the client browser. Usually one of the controls on the page will be manipulated by the user (a button clicked or dropdown changed, etc), and this control will initiate a postback. The state of this control, plus all other controls on the page,(known as the View State) isPosted Back to the web server.
What happens?
Most commonly the postback causes the web server to create an instance of the code behind class of the page that initiated the postback. This page object is then executed within the normal page lifecycle with a slight difference (see below). If you do not redirect the user specifically to another page somewhere during the page lifecycle, the final result of the postback will be the same page displayed to the user again, and then another postback could happen, and so on.
Why does it happen?
The web application is running on the web server. In order to process the user’s response, cause the application state to change, or move to a different page, you need to get some code to execute on the web server. The only way to achieve this is to collect up all the information that the user is currently working on and send it all back to the server.
Some things for a beginner to note are...
- The state of the controls on the posting back page are available within the context. This will allow you to manipulate the page controls or redirect to another page based on the information there.
- Controls on a web form have events, and therefore event handlers, just like any other controls. The initialisation part of the page lifecycle will execute before the event handler of the control that caused the post back. Therefore the code in the page’s Init and Load event handler will execute before the code in the event handler for the button that the user clicked.
- The value of the “Page.IsPostBack” property will be set to “true” when the page is executing after a postback, and “false” otherwise.
- Technologies like Ajax and MVC have changed the way postbacks work.