5.4 由JavaScript來更新UpdatePanel
經過了Single Page架構的震撼教育后,讓我們輕松一點談談UpdatePanel的更新動作控制,除了可以通過Trigger、Update函數來更新UpdatePanel外,設計師也能通過JavaScript,從客戶端要求更新某一個UpdatePanel,這在許多情況下會相當的有用。那具體該如何做呢?說來也很簡單,只要在JavaScript調用__doPostback函數,傳入要更新的UpdatePanel即可,程序5-10是本例所使用的.aspx源碼,程序5-11則是.cs文件。
程序5-10
Samples\5\AdvAjaxDemo\RefreshUpdateWithJavaScript2.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile= "RefreshUpdateWithJavaScript2.aspx.cs" Inherits= "RefreshUpdateWithJavaScript2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <script language=javascript> function confirmRefresh() { if(confirm("do you want refresh?")) { __doPostback("UpdatePanel1","Refresh"); } } </script> <input id="Button1" type="button" value="Refresh Panel" onclick= "confirmRefresh()"/> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </ContentTemplate> </asp:UpdatePanel> </div> </form> </body> </html>
程序5-11
Samples\5\AdvAjaxDemo\RefreshUpdateWithJavaScript2.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class RefreshUpdateWithJavaScript2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (ScriptManager1.IsInAsyncPostback && ScriptManager1.AsyncPostbackSourceElementID == "UpdatePanel1") { Label1.Text = DateTime.Now.ToString(); } } }
很簡單不是?