UpdatePanel可以用来创建丰富的局部更新Web应用程序,它是ASP.NET 2.0 AJAX Extensions中很重要的一个控件,其强大之处在于不用编写任何客户端脚本,只要在一个页面上添加几个UpdatePanel控件和一个ScriptManager控件就可以自动实现局部更新。通过本文来学习一下UpdatePanel简单的使用方法 。
主要内容
1.UpdatePanel控件概述
2.UpdatePanel工作原理
3.ContentTemplate属性
4.ContentTemplateContainer属性
5.Triggers属性
6.用编程的方法控制UpdatePanel的更新
7.UpdatePanel的嵌套使用
8.同一页面上使用多个UpdatePanel
一.UpdatePanel控件概述
UpdatePanel可以用来创建丰富的局部更新Web应用程序,它是ASP.NET 2.0 AJAX Extensions中很重要的一个控件,其强大之处在于不用编写任何客户端脚本,只要在一个页面上添加几个UpdatePanel控件和一个ScriptManager控件就可以自动实现局部更新。通过本文来学习一下UpdatePanel工作原理和使用方法。简单的UpdatePanel定义如下:重要的属性如下:
<
asp:UpdatePanel
ID
="UpdatePanel1"
runat
="server"
>

<
ContentTemplate
>


ContentTemplate
>

<
Triggers
>

<
asp:AsyncPostBackTrigger
/>

<
asp:PostBackTrigger
/>

Triggers
>

asp:UpdatePanel
>
UpdatePanel
属性 |
说明 |
ChildrenAsTriggers |
当UpdateMode属性为Conditional时,UpdatePanel中的子控件的异步回送是否会引发UpdatePanle的更新。 |
RenderMode |
表示UpdatePanel最终呈现的HTML元素。Block(默认)表示,Inline表示 |
UpdateMode |
表示UpdatePanel的更新模式,有两个选项:Always和Conditional。Always是不管有没有Trigger,其他控件都将更新该UpdatePanel,Conditional表示只有当前UpdatePanel的Trigger,或ChildrenAsTriggers属性为true时当前UpdatePanel中控件引发的异步回送或者整页回送,或是服务器端调用Update()方法才会引发更新该UpdatePanel。 |
二.UpdatePanel工作原理
UpdatePanel的工作依赖于ScriptManager服务端控件(ASP.NET AJAX入门系列(2):使用ScriptManager控件)和客户端PageRequestManager类(Sys.WebForms.PageRequestManager,在后面的客户端类中会专门说到),当ScriptManager中允许页面局部更新时,它会以异步的方式回传给服务器,与传统的整页回传方式不同的是只有包含在UpdatePanel中的页面部分会被更新,在从服务端返回HTML之后,PageRequestManager会通过操作DOM对象来替换需要更新的代码片段。
看一下官方网站提供的UpdatePanel工作原理图:
三.ContentTemplate属性
Contente Template标签用来定义UpdatePanel的内容,在它里面可以放任何ASP.NET元素。如果你想要使用编程的手法来控制UpdatePanel中的内容,就需要使用ContenteTemplateContainer,下面会说到,先来看一个简单的ContentTemplate的例子。四.ContentTemplateContainer属性
<
asp:UpdatePanel
ID
="UpdatePanel1"
runat
="server"
>

<
ContentTemplate
>

<
asp:Calendar
ID
="Calendar1"
ShowTitle
="True"
runat
="server"
/>

<
div
>

Background:

<
br
/>

<
asp:DropDownList
ID
="ColorList"
AutoPostBack
="True"
OnSelectedIndexChanged
="DropDownSelection_Change"

runat
="server"
>

<
asp:ListItem
Selected
="True"
Value
="White"
>

White
asp:ListItem
>

<
asp:ListItem
Value
="Silver"
>

Silver
asp:ListItem
>

<
asp:ListItem
Value
="DarkGray"
>

Dark Gray
asp:ListItem
>

<
asp:ListItem
Value
="Khaki"
>

Khaki
asp:ListItem
>

<
asp:ListItem
Value
="DarkKhaki"
>
D

ark Khaki
asp:ListItem
>

asp:DropDownList
>

div
>

ContentTemplate
>

asp:UpdatePanel
>
事件代码:
<
script
runat
="server"
>

void DropDownSelection_Change(Object sender, EventArgs e)


{

Calendar1.DayStyle.BackColor =

System.Drawing.Color.FromName(ColorList.SelectedItem.Value);

}

script
>
如果要使用编程的手法去设置UpdatePanel中的内容,需要创建一个UpdatePanel,并且添加控件到ContentTemplateContainer,而不能直接添加控件到ContentTemplate,如果想直接设置ContentTemplate,则需要编写一个自定义的Template,并去实现位于System.Web.UI命名空间下的接口ITemplate。看一个简单的来自于官方网站的例子:
<%
@ Page Language="C#"
%>


<
script
runat
="server"
>

protected void Page_Load(object sender, EventArgs e)


{

UpdatePanel up1 = new UpdatePanel();

up1.ID = "UpdatePanel1";

up1.UpdateMode = UpdatePanelUpdateMode.Conditional;

Button button1 = new Button();

button1.ID = "Button1";

button1.Text = "Submit";

button1.Click += new EventHandler(Button_Click);

Label label1 = new Label();

label1.ID = "Label1";

label1.Text = "A full page postback occurred.";

up1.ContentTemplateContainer.Controls.Add(button1);

up1.ContentTemplateContainer.Controls.Add(label1);

Page.Form.Controls.Add(up1);

}

protected void Button_Click(object sender, EventArgs e)


{

((Label)Page.FindControl("Label1")).Text = "Panel refreshed at " +

DateTime.Now.ToString();

}

script
>

<
html
xmlns
="http://www.w3.org/1999/xhtml"
>

<
head
id
="Head1"
runat
="server"
>

<
title
>
UpdatePanel Added Programmatically Example
title
>

head
>

<
body
>

<
form
id
="form1"
runat
="server"
>

<
div
>

<
asp:ScriptManager
ID
="TheScriptManager"

runat
="server"
/>

div
>

form
>

body
>

html
>
五.Triggers属性
在ASP.NET AJAX中有两种Triggers:分别为AsyncPostBackTrigger和PostBackTrigger,AsyncPostBackTrigge用来指定某个服务器端控件以及其将触发的服务器端事件作为该UpdatePanel的异步更新触发器,它需要设置的属性有控件ID和服务端控件的事件;PostBackTrigger用来指定在UpdatePanel中的某个服务端控件,它所引发的回送不使用异步回送,而仍然是传统的整页回送。这一点跟Atlas有很大的区别,大家需要注意。看一个小例子,虽然两个Button都放在了UpdatePanel中,但是由于在PostBackTrigger中指定了Button2,所以它使用的仍然是整页回送。
<%
@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2"
%>


<
script
runat
="server"
>

void Button1_Click(object sender, EventArgs e)


{
this.Label1.Text = "更新时间:" + System.DateTime.Now.ToString();
}

void Button2_Click(object sender, EventArgs e)


{
this.Label1.Text = "更新时间:" + System.DateTime.Now.ToString();
}

script
>

<
html
xmlns
="http://www.w3.org/1999/xhtml"
>

<
head
runat
="server"
>

<
title
>
UpdatePanel Trigger Sample
title
>

head
>

<
body
>

<
form
id
="form1"
runat
="server"
>

<
div
>

<
asp:ScriptManager
ID
="ScriptManager1"
runat
="server"
>

asp:ScriptManager
>

div
>

<
asp:UpdatePanel
ID
="UpdatePanel1"
runat
="server"
>

<
ContentTemplate
>

<
div
>

<
asp:Button
ID
="Button1"
runat
="server"
Text
="异步回送"
OnClick
="Button1_Click"
/>

<
asp:Button
ID
="Button2"
runat
="server"
Text
="整页回送"
OnClick
="Button2_Click"
/><
br
/>

<
br
/>

<
asp:Label
ID
="Label1"
runat
="server"
Text
="当前时间"
Font-Bold
="True"
Font-Size
="Large"
>
asp:Label
>
div
>

ContentTemplate
>

<
Triggers
>

<
asp:AsyncPostBackTrigger
ControlID
="Button1"
/>

<
asp:PostBackTrigger
ControlID
="Button2"
/>

Triggers
>

asp:UpdatePanel
>

form
>

body
>

html
>
六.用编程的方法控制UpdatePanel的更新
对于UpdatePanel,我们也可以使用编程的方法来控制它的更新,可以通过ScriptManager的RegisterAsyncPostBackControl()方法注册一个异步提交的控件,并且调用UpdatePanel的Update()方法来让它更新。再次用我在前面的文章中用到的一个无聊的时间更新例子来看一下,有时候我觉得例子过于复杂更加不好说明白所要讲的内容,如下代码所示,注意Button1并不包含在UpdatePanel中:
<%
@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
%>


<
script
runat
="server"
>

void Button1_Click(object sender, EventArgs e)


{

this.Label2.Text = DateTime.Now.ToString();

}

script
>

<
html
xmlns
="http://www.w3.org/1999/xhtml"
>

<
head
runat
="server"
>

<
title
>
Refreshing an UpdatePanel Programmatically
title
>

head
>

<
body
>

<
form
id
="form1"
runat
="server"
>

<
asp:ScriptManager
ID
="ScriptManager1"
runat
="server"
/>

<
div
>

<
asp:UpdatePanel
ID
="UpdatePanel1"
runat
="server"
UpdateMode
="Conditional"
>

<
ContentTemplate
>

<
asp:Label
ID
="Label1"
runat
="server"
Text
="更新时间:"
>
asp:Label
>

<
asp:Label
ID
="Label2"
runat
="server"
Text
="Label"
ForeColor
="Red"
>
asp:Label
><
br
/><
br
/>


ContentTemplate
>

asp:UpdatePanel
>

<
asp:Button
ID
="Button1"
runat
="server"
Text
="Button"
OnClick
= "Button1_Click"
/>

div
>

form
>

body
>

html
>
这时候不用多说,肯定是整页提交了,运行如下图所示:
再次修改上面的例子,使用ScriptManager的RegisterAsyncPostBackControl()注册Button1为一个异步提交控件,并且调用UpdatePanel的Update()方法:
<%
@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
%>


<
script
runat
="server"
>

void Page_Load(object sender, EventArgs e)


{

ScriptManager1.RegisterAsyncPostBackControl(Button1);

}


void Button1_Click(object sender, EventArgs e)


{

this.Label2.Text = DateTime.Now.ToString();

this.UpdatePanel1.Update();

}

script
>

<
html
xmlns
="http://www.w3.org/1999/xhtml"
>

<
head
runat
="server"
>

<
title
>
Refreshing an UpdatePanel Programmatically
title
>

head
>

<
body
>

<
form
id
="form1"
runat
="server"
>

<
asp:ScriptManager
ID
="ScriptManager1"
runat
="server"
/>

<
div
>

<
asp:UpdatePanel
ID
="UpdatePanel1"
runat
="server"
UpdateMode
="Conditional"
>

<
ContentTemplate
>

<
asp:Label
ID
="Label1"
runat
="server"
Text
="更新时间:"
>
asp:Label
>

<
asp:Label
ID
="Label2"
runat
="server"
Text
="Label"
ForeColor
="Red"
>
asp:Label
><
br
/><
br
/>


ContentTemplate
>

asp:UpdatePanel
>

<
asp:Button
ID
="Button1"
runat
="server"
Text
="Button"
OnClick
= "Button1_Click"
/>

div
>

form
>

body
>

html
>
这时候可以看到,已经是异步提交了:
七. UpdatePanel的嵌套使用
UpdatePanel还可以嵌套使用,即在一个UpdatePanel的ContentTemplate中还可以放入另一个UpdatePanel。当最外面的UpdatePanel被触发更新时,它里面的子UpdatePanel也随着更新,里面的UpdatePanel触发更新时,只更新它自己,而不会更新外层的UpdatePanel。看下面的例子:
<%
@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2"
%>


<
script
runat
="server"
>

script
>


<
html
xmlns
="http://www.w3.org/1999/xhtml"
>

<
head
id
="Head1"
runat
="server"
>

<
title
>
UpdatePanelUpdateMode Example
title
>


<
style
type
="text/css"
>

div.NestedPanel


{
}{

position: relative;

margin: 2% 5% 2% 5%;

}

style
>

head
>

<
body
>

<
form
id
="form1"
runat
="server"
>

<
div
>

<
asp:ScriptManager
ID
="ScriptManager"

runat
="server"
/>

<
asp:UpdatePanel
ID
="OuterPanel"

UpdateMode
="Conditional"

runat
="server"
>

<
ContentTemplate
>

<
div
>

<
fieldset
>

<
legend
>
Outer Panel
legend
>

<
br
/>

<
asp:Button
ID
="OPButton1"

Text
="Outer Panel Button"

runat
="server"
/>

<
br
/>

Last updated on

<%
=
DateTime.Now.ToString()
%>

<
br
/>

<
br
/>

<
asp:UpdatePanel
ID
="NestedPanel1"

UpdateMode
="Conditional"

runat
="server"
>

<
ContentTemplate
>

<
div
class
="NestedPanel"
>

<
fieldset
>

<
legend
>
Nested Panel 1
legend
>

<
br
/>

Last updated on

<%
=
DateTime.Now.ToString()
%>

<
br
/>

<
asp:Button
ID
="NPButton1"

Text
="Nested Panel 1 Button"

runat
="server"
/>

fieldset
>

div
>

ContentTemplate
>

asp:UpdatePanel
>

fieldset
>

div
>

ContentTemplate
>

asp:UpdatePanel
>

div
>

form
>

body
>

html
>
运行后如下:
八.同一页面上使用多个UpdatePanel
使用UpdatePanel的时候并没有限制在一个页面上用多少个UpdatePanel,所以我们可以为不同的需要局部更新的页面区域加上不同的UpdatePanel。由于UpdatePanel默认的UpdateMode是Always,如果页面上有一个局部更新被触发,则所有的UpdatePanel都将更新,这是我们不愿看到的,我们只需要UpdatePanel在它自己的触发器触发的时候更新就可以了,所以需要把UpdateMode设置为Conditional。
来看一下官方网站上提供的一个例子:包括两个UpdatePanel,其中一个用来用户输入而另一个则用来显示数据,每一个UpdatePanel的UpdateMode属性都设置为Conditional。当我们单击Cancel按钮时,只有用来用户输入的那个UpdatePanel刷新,当单击Insert按钮时,两个UpdatePanel都刷新。代码如下:
<%
@ Page Language="C#"
%>


<%
@ Import Namespace="System.Collections.Generic"
%>


<
html
xmlns
="http://www.w3.org/1999/xhtml"
>

<
head
id
="Head1"
runat
="server"
>

<
title
>
Enter New Employees
title
>


<
script
runat
="server"
>

private List<Employee> EmployeeList;


protected void Page_Load()


{

if (!IsPostBack)


{

EmployeeList = new List<Employee>();

EmployeeList.Add(new Employee(1, "Jump", "Dan"));

EmployeeList.Add(new Employee(2, "Kirwan", "Yvette"));

ViewState["EmployeeList"] = EmployeeList;

}

else

EmployeeList = (List<Employee>)ViewState["EmployeeList"];


EmployeesGridView.DataSource = EmployeeList;

EmployeesGridView.DataBind();

}


protected void InsertButton_Click(object sender, EventArgs e)


{

if (String.IsNullOrEmpty(FirstNameTextBox.Text) ||


String.IsNullOrEmpty(LastNameTextBox.Text))
{ return; }


int employeeID = EmployeeList[EmployeeList.Count-1].EmployeeID + 1;


string lastName = Server.HtmlEncode(FirstNameTextBox.Text);

string firstName = Server.HtmlEncode(LastNameTextBox.Text);


FirstNameTextBox.Text = String.Empty;

LastNameTextBox.Text = String.Empty;


EmployeeList.Add(new Employee(employeeID, lastName, firstName));

ViewState["EmployeeList"] = EmployeeList;


EmployeesGridView.DataBind();

EmployeesGridView.PageIndex = EmployeesGridView.PageCount;

}


protected void CancelButton_Click(object sender, EventArgs e)


{

FirstNameTextBox.Text = String.Empty;

LastNameTextBox.Text = String.Empty;

}


[Serializable]

public class Employee


{

private int _employeeID;

private string _lastName;

private string _firstName;


public int EmployeeID


{


get
{ return _employeeID; }

}


public string LastName


{


get
{ return _lastName; }

}


public string FirstName


{


get
{ return _firstName; }

}


public Employee(int employeeID, string lastName, string firstName)


{

_employeeID = employeeID;

_lastName = lastName;

_firstName = firstName;

}

}


script
>

head
>

<
body
>

<
form
id
="form1"
runat
="server"
>

<
div
>

div
>

<
asp:ScriptManager
ID
="ScriptManager1"
runat
="server"
EnablePartialRendering
="true"
/>

<
table
>

<
tr
>

<
td
style
="height: 206px"
valign
="top"
>

<
asp:UpdatePanel
ID
="InsertEmployeeUpdatePanel"
runat
="server"
UpdateMode
="Conditional"
>

<
ContentTemplate
>

<
table
cellpadding
="2"
border
="0"
style
="background-color:#7C6F57"
>

<
tr
>

<
td
><
asp:Label
ID
="FirstNameLabel"
runat
="server"
AssociatedControlID
="FirstNameTextBox"

Text
="First Name"
ForeColor
="White"
/>
td
>

<
td
><
asp:TextBox
runat
="server"
ID
="FirstNameTextBox"
/>
td
>

tr
>

<
tr
>

<
td
><
asp:Label
ID
="LastNameLabel"
runat
="server"
AssociatedControlID
="LastNameTextBox"

Text
="Last Name"
ForeColor
="White"
/>
td
>

<
td
><
asp:TextBox
runat
="server"
ID
="LastNameTextBox"
/>
td
>

tr
>

<
tr
>

<
td
>
td
>

<
td
>

<
asp:LinkButton
ID
="InsertButton"
runat
="server"
Text
="Insert"
OnClick
="InsertButton_Click"
ForeColor
="White"
/>

<
asp:LinkButton
ID
="Cancelbutton"
runat
="server"
Text
="Cancel"
OnClick
="CancelButton_Click"
ForeColor
="White"
/>

td
>

tr
>

table
>

<
asp:Label
runat
="server"
ID
="InputTimeLabel"
>
<%
=
DateTime.Now
%>
asp:Label
>

ContentTemplate
>

asp:UpdatePanel
>

td
>

<
td
style
="height: 206px"
valign
="top"
>

<
asp:UpdatePanel
ID
="EmployeesUpdatePanel"
runat
="server"
UpdateMode
="Conditional"
>

<
ContentTemplate
>

<
asp:GridView
ID
="EmployeesGridView"
runat
="server"
BackColor
="LightGoldenrodYellow"
BorderColor
="Tan"

BorderWidth
="1px"
CellPadding
="2"
ForeColor
="Black"
GridLines
="None"
AutoGenerateColumns
="False"
>

<
FooterStyle
BackColor
="Tan"
/>

<
SelectedRowStyle
BackColor
="DarkSlateBlue"
ForeColor
="GhostWhite"
/>

<
PagerStyle
BackColor
="PaleGoldenrod"
ForeColor
="DarkSlateBlue"
HorizontalAlign
="Center"
/>

<
HeaderStyle
BackColor
="Tan"
Font-Bold
="True"
/>

<
AlternatingRowStyle
BackColor
="PaleGoldenrod"
/>

<
Columns
>

<
asp:BoundField
DataField
="EmployeeID"
HeaderText
="Employee ID"
/>

<
asp:BoundField
DataField
="LastName"
HeaderText
="Last Name"
/>

<
asp:BoundField
DataField
="FirstName"
HeaderText
="First Name"
/>

Columns
>

<
PagerSettings
PageButtonCount
="5"
/>

asp:GridView
>

<
asp:Label
runat
="server"
ID
="ListTimeLabel"
>
<%
=
DateTime.Now
%>
asp:Label
>

ContentTemplate
>

<
Triggers
>

<
asp:AsyncPostBackTrigger
ControlID
="InsertButton"
EventName
="Click"
/>

Triggers
>

asp:UpdatePanel
>

td
>

tr
>

table
>

form
>

body
>

html
>
运行后效果如下: