共用方式為


從伺服器程式碼啟動強制回應快顯視窗 (C#)

作者 :一個是一個

下載 PDF

AJAX 控制項工具組中的 ModalPopup 控制項提供使用用戶端方法建立強制回應快顯的簡單方式。 不過,某些案例會要求在伺服器端觸發開啟強制回應快顯。

概觀

AJAX 控制項工具組中的 ModalPopup 控制項提供使用用戶端方法建立強制回應快顯的簡單方式。 不過,某些案例會要求在伺服器端觸發開啟強制回應快顯。

步驟

首先,需要 ASP.NET Button Web 控制項,才能示範 ModalPopup 控制項的運作方式。 在新頁面上的表單 > 元素內 < 新增這類按鈕:

<asp:Button ID="ClientButton" runat="server" Text="Launch Modal Popup (Client)" />

然後,您需要要建立之快顯視窗的標記。 將它 <asp:Panel> 定義為控制項,並確定它包含 Button 控制項。 ModalPopup 控制項提供讓這類按鈕關閉快顯的功能;否則,就無法輕易地讓它消失。

<asp:Panel ID="ModalPanel" runat="server" Width="500px">
 ASP.NET AJAX is a free framework for quickly creating a new generation of more 
 efficient, more interactive and highly-personalized Web experiences that work 
 across all the most popular browsers.<br />
 <asp:Button ID="OKButton" runat="server" Text="Close" />
</asp:Panel>

接下來,將 ModalPopup 控制項從 ASP.NET AJAX Toolkit 新增至頁面。 設定載入控制項之按鈕的屬性、讓它消失的按鈕,以及實際快顯視窗的識別碼。

<ajaxToolkit:ModalPopupExtender ID="mpe" runat="server" TargetControlId="ClientButton" 
 PopupControlID="ModalPanel" OkControlID="OKButton" />

如同以 ASP.NET AJAX 為基礎的所有網頁;需要腳本管理員,才能載入不同目標瀏覽器所需的 JavaScript 程式庫:

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

在瀏覽器中執行範例。 當您按一下按鈕時,模式快顯視窗隨即出現。 若要使用伺服器端程式碼達到相同的效果,需要新的按鈕:

<asp:Button ID="ServerButton" runat="server" Text="Launch Modal Popup (Server)" 
 OnClick="ServerButton_Click" />

如您所見,按一下按鈕會產生回傳,並在伺服器上執行 ServerButton_Click() 方法。 在此方法中,呼叫 launchModal() 的 JavaScript 函式會執行為精確,一旦載入頁面,就會執行 JavaScript 函式:

<script runat="server">
 protected void ServerButton_Click(object sender, EventArgs e)
 {
 ClientScript.RegisterStartupScript(this.GetType(), "key", "launchModal();", true);
 }
</script>

launchModal() 作業是顯示 ModalPopup。 載入完整的 HTML 頁面之後,就會執行函 launchModal() 式。 不過,目前尚未完整載入 ASP.NET AJAX 架構。 因此,函 launchModal() 式只會設定 ModalPopup 控制項稍後必須顯示的變數:

<script type="text/javascript">
 var launch = false;
 function launchModal() 
 {
 launch = true;
 }

JavaScript 函 pageLoad() 式是一種特殊函式,一旦完整載入 AJAX ASP.NET 就會執行。 因此,我們會將程式碼新增至此函式以顯示 ModalPopup 控制項,但只有在之前已呼叫 時 launchModal()

function pageLoad() 
 {
 if (launch) 
 {
 $find("mpe").show();
 }
 }
</script>

$find() 式正在頁面上尋找具名元素,並預期伺服器端識別碼為參數。 因此, $find("mpe") 會傳回 ModalPopup 控制項的用戶端標記法;其 show() 方法可讓快顯視窗出現。

按一下任一按鈕時,會出現強制回應快顯視窗

按一下任一按鈕 (按一下即可檢視完整大小的影像 時,會顯示強制回應快顯視窗)