ASP.NET中用编程的方法控制UpdatePanel的更新
UpdatePanel可以用来创建丰富的局部更新Web应用程序,它是ASP.NET 2.0 AJAX Extensions中很重要的一个控件。对于UpdatePanel,我们也可以使用编程的方法来控制它的更新,可以通过ScriptManager的RegisterAsyncPostBackControl()方法注册一个异步提交的控件,并且调用UpdatePanel的Update()方法来让它更新。再次用我在前面的文章中用到的一个无聊的时间更新例子来看一下,有时候我觉得例子过于复杂更加不好说明白所要讲的内容,如下代码所示,注意Button1并不包含在UpdatePanel中:
- <%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default
.aspx.cs"Inherits="_Default"%>- <scriptrunatscriptrunat="server">
- voidButton1_Click(objectsender,EventArgse)
- {
- this.Label2.Text=DateTime.Now.ToString();
- }
- < SPAN>script>
- <htmlxmlnshtmlxmlns="http://www.w3.org/1999/xhtml">
- <headrunatheadrunat="server">
- <title>RefreshinganUpdatePanelProgrammatically< SPAN>title>
- < SPAN>head>
- <body>
- <formidformid="form1"runat="server">
- <asp:ScriptManagerIDasp:ScriptManagerID="ScriptManager1
"runat="server"/>- <div>
- <asp:UpdatePanelIDasp:UpdatePanelID="UpdatePanel1"runat=
"server"UpdateMode="Conditional">- <ContentTemplate>
- <asp:LabelIDasp:LabelID="Label1"runat="server"Text=
"更新时间:">< SPAN>asp:Label>- <asp:LabelIDasp:LabelID="Label2"runat="server"Text=
"Label"ForeColor="Red">< SPAN>asp:Label><br/><br/>- < SPAN>ContentTemplate>
- < SPAN>asp:UpdatePanel>
- <asp:ButtonIDasp:ButtonID="Button1"runat="server"Text=
"Button"OnClick="Button1_Click"/>- < SPAN>div>
- < SPAN>form>
- < SPAN>body>
- < SPAN>html>
再次修改上面的例子,使用ScriptManager的RegisterAsyncPostBackControl()注册Button1为一个异步提交控件,并且调用UpdatePanel的Update()方法:
- <%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"
Inherits="_Default"%>- <scriptrunatscriptrunat="server">
- voidPage_Load(objectsender,EventArgse)
- {
- ScriptManager1.RegisterAsyncPostBackControl(Button1);
- }
- voidButton1_Click(objectsender,EventArgse)
- {
- this.Label2.Text=DateTime.Now.ToString();
- this.UpdatePanel1.Update();
- }
- < SPAN>script>
- <htmlxmlnshtmlxmlns="http://www.w3.org/1999/xhtml">
- <headrunatheadrunat="server">
- <title>RefreshinganUpdatePanelProgrammatically< SPAN>title>
- < SPAN>head>
- <body>
- <formidformid="form1"runat="server">
- <asp:ScriptManagerIDasp:ScriptManagerID="ScriptManager1"runat="server"/>
- <div>
- <asp:UpdatePanelIDasp:UpdatePanelID="UpdatePanel1"runat=
"server"UpdateMode="Conditional">- <ContentTemplate>
- <asp:LabelIDasp:LabelID="Label1"runat="server"Text="更新时间:">< SPAN>asp:Label>
- <asp:LabelIDasp:LabelID="Label2"runat="server"Text="Label"ForeColor
="Red">< SPAN>asp:Label><br/><br/>- < SPAN>ContentTemplate>
- < SPAN>asp:UpdatePanel>
- <asp:ButtonIDasp:ButtonID="Button1"runat="server"Text=
"Button"OnClick="Button1_Click"/>- < SPAN>div>
- < SPAN>form>
- < SPAN>body>
- < SPAN>html>
以上是ASP.NET调用UpdatePanel的Update()方法
【编辑推荐】