浅谈ASP.NET的Postback
[2] 浅谈ASP.NET的Postback
这篇Blog的主旨就是从方法调用的角度讲述整个程序运行的过程:从HTML 被Render到Client端,到用户Click某个按钮,输入被Postback到Server端,并触发两个Event,执行Event Handler打印出相关的Message。
首先我们来看看ASP.NET设计的Page Render到Client端的HTML是什么样子:













0NDQ2OTE5OWRk281L4eAk7iZT10hzg+BeOyoUWBQ=" />












n2','')" id="Button2" />

n3','')" id="Button3" />





上面的HTMLBody部分大体包括3个部分:
1. 定义了3个hidden field:



OWRk281L4eAk7iZT10hzg+BeOyoUWBQ=" />

从他们的命名可以看出他们分别代表的意思:__EVENTTARGET代表触发Event的Control的Unique name;__EVENTARGUMENT代表为Event Handler定义的额外的参数;__VIEWSTATE:代表的是Viewstate。
2. 一段script:




3. 一段HTML对应通过ASP.NET定义的Web Control。






n2','')" id="Button2" />

n3','')" id="Button3" />


我们定义的3个Button被转化成3个能向Server端提交表单的 Tag, 但是他们提交表的方式却不一样,第一个以的方式提交,后面两个通过调用javascript的方式提交表单()。对于一个System.Web.UI.WebControls.Button,默认采用第一种提交方式,但是我们通过设置UseSubmitBehavior属性(这个属性时ASP.NET 2.0新加的,1x没有相应的设置),改变其表单提交的行为。
当用户Click Button2的时候,调用__doPostBack,并传入两个参数:一个代表出发Event的对象的Unique name,也就是Button2的名称,另一个描述Event的额外信息的参数,这里不需要,所以这里是空字符串。在__doPostBack中把这两个参数赋值给两个Hidden Field:__EVENTTARGET,__EVENTARGUMENT。然后向Server端提交表单,完成Postback。
然后我们来看看Server如何处理这个Postback,关于Web Page的生命周期在这里就不详细介绍了。Server端通过__EVENTTARGET这个hidden field的值找到对应的Server端的Control,通过Reflection确定该Control是否实现了System.Web.UI.IPostBackEventHandler Interface。如果该Control确实实现了该Interface,那么调用Page的RaisePostBackEvent方法,这是一个Virtual的方法,可以被Override。我们来看该方法的定义。


ment)




我们可以看到该方法直接调用该sourceControl的RaisePostBackEvent,并传入一个eventArgument参数,在这个例子中sourceControl就是__EVENTTARGET对应的Web Control:Button2,eventArgument就是__EVENTTARGET对应的值:一个空字符串。Button2的类型是System.Web.UI.WebControls.Button。我们来看看System.Web.UI.WebControls.Button中的RaisePostBackEvent方法是如何定义的:











这个方法也很简单,先进行Validation,然后先后出发两个Event:OnClick 和OnCommand,随后调用对应的Event handler,这和我们的输出结果是吻合的。
这基本上就是整个Postback的整个程序执行的过程,现在我们对我们的Page作一些小的有趣的改动,来验证一下:
Client端和Server端进行交互的途径就是提交表单(Form Submitting),而我们现在有两种方式来提交表单:通过控件;通过调用javascript:__doPostBack。基于这一点我们在Html中加了下面一段javascript:











我们override Button2和Button3的onclick event,把'Button1作为参数传入__doPostBack方法,可以想象,现在无论Click那个Button,程序都将认为之Click Button1。有兴趣的可以亲自试试,无论Click那个Button,显示的效果都将是下面的样子:
接下来我们取消上面的改动,在Server对Code作另一方面的尝试。我们前面说过,Server接受到Client的Postback,对于事件的Web Control(或者Html Server Control),如果实现了System.Web.UI.IPostBackEventHandler接口,会调用Page的virtual方法:RaisePostbackEvent,我们现在来Override这个方法:

ument)





在上面的Code中,我们把sourceControl设为Button1,这样无论在client端Click的那个Button,现在都将认为是对Button的Click。运行的结果和上面一样。
通过上面的介绍,我们知道了Page的RaisePostBackEvent会调用Source Control的RaisePostBackEvent方法,这个方法是定义在IPostBackEventHandler接口中,很多Control都实现了这个方法,对于Button来说,这个方法是Virtual的,它可以被你Override,如果感兴趣的话,可以自己写一个Custom Button,并Override该方法,看看执行的情况,相信会使加深你对Postback的理解。