决战.NET
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人

2.4 UpdateMode与UpdateTriggers

UpdateMode

不知读者们是否已经查觉,前文在谈论UpdatePanel控件的刷新时,特别注明当UpdatePanel控件中的子控件触发Async-Postback动作时,刷新的区域是“涵盖网页上的所有将UpdateMode设为Always的UpdatePanel控件”,而不是单单只有触发Async-Postback的那个UpdatePanel控件。这意味着当Async-Postback动作发生时,ASP.NET AJAX会更新所有UpdateMode设为Always的UpdatePanel控件内容,可以想见,当页面上有很多个UpdatePanel控件时,对效率会产生多大的影响!解决办法是将UpdatePanel控件的UpdateMode属性设为Conditional,交由Triggers或程序来控制该UpdatePanel控件的刷新。

UpdateTrigger

当UpdateMode设为Conditional后,UpdateTriggers属性的设定就显得更加重要,只有UpdateTriggers中所设定的控件发生Async-Postback动作时,此UpdatePanel控件才会刷新。默认情况下,UpdatePanel控件的ChildrenAsTriggers属性值设为True,意味着位于此UpdatePanel控件中的子控件会自动成为UpdateTriggers的一部分,也就是说只要这些子控件发生Postback动作,这个Postback动作将变成Async-Postback动作,完成后就会刷新此UpdatePanel中的内容。适当地利用UpdateMode及UpdateTriggers,可以对UpdatePanel控件的刷新做更细致的调整和更有效率的应用,请开启第2、3节中所创建的网站,并照下列步骤操作,如图2-17所示。

true

图2-17

1. 新建一个网页。

2. 于网页中放入ScriptManager控件。

3. 放入UpdatePanel控件,ID设定为UpdatePanel1。

4. 将UpdatePanel1的UpdateMode属性设为Conditional。

5. 放一个SqlDataSource控件至UpdatePanel1,ID设为SqlDataSource1,链接至Northwind数据库中的Customers数据表,并配置成可编辑的DataSource。

6. 放一个GridView控件至UpdatePanel1中,将DataSourceID设为SqlDataSource1,勾选“Enable Paging”及“Enable Editing”选项。

7. 加一个Button控件于UpdatePanel1控件外面,名为Button1,在其Click事件中键入程序2-5的程序代码。

程序2-5

    Samples\2\SecondAjax\UseTriggers.aspx.cs
    protected void Button1_Click(object sender, EventArgs e)
    {
        GridView1.EditIndex = 4;
        GridView1.DataBind();
    }

在UpdatePanel默认的行为中,这个Button控件并非位于任何UpdatePanel控件内,因此其Postback动作将会导致整个网页的刷新,但若借助于UpdatePanel控件所提供的Trigger功能,便可将其设定为触发Postback后,要求特定的UpdatePanel控件进行刷新动作。请点击UpdatePanel控件的Triggers属性,点击“Add”按钮新增一个Trigger,将ControlID属性设为Button1,EventName属性则设为Click,如图2-18所示。

true

图2-18

这个Trigger设定的意思是,当Button1按钮发生Postback时,这个Postback动作将被视为Async-Postback动作,当此动作送至Server后,UpdatePanel控件会判断送出此Async-Postback动作的控件是否在Triggers设定中,再判断事件名称是否符合,两者皆符合时,此UpdatePanel控件便会进行刷新动作,当某个Trigger未设定事件名称时,意味着不管该控件发生任何Postback动作,都会触发UpdatePanel的刷新。请将此网页设为Start Page(起始网页)后运行此程序,如图2-19所示。

点击Button按钮后,你便会察觉到网页只会刷新位于UpdatePanel控件中的GridView控件的状态而已,也就是GridView控件会进入编辑第四行的状态。请特别注意!这个Button并未放在UpdatePanel控件中,这也就是说即使于Click事件中修改其Text属性值,也不会在点击按钮后立即显示所修改的值,不过由于UpdatePanel控件的行为模式,这个修改值的动作其实已经完成,只要下次有页面刷新情况发生时,还是会看到这个修改后的值。

true

图2-19