Welcome

首页 / 脚本样式 / Ajax / 使用AJAX的模式对话框

使用AJAX的模式对话框2010-03-02 MSDN Dino Esposito目录

ModalPopupExtender 控件

使用 Esc 键关闭弹出框

添加动画显示

将数据返回到服务器

请您登场

对话框在 Windows® 中已使用了很长时间,它们确实具有自己的优势。但是,如果您希望 Web 应用程序拥有对话框,它们基本上是弹出框,您知道,大多数用户都会使用拦截程序禁用弹出框。那么,如果您需要弹出框将要怎么办?

使用 Microsoft® ASP.NET AJAX 时,如果没有页面重新加载或新页面,对话框对于显示上下文相关信息尤其重要。因此,非常有必要设计这样一种对话框,它与模式弹出框等效,并且让用户使用起来十分方便。

ASP.NET 和 AJAX 扩展都不具有对弹出框或 Web 对话框的内置支持,但 AJAX 控件工具包却具有。AJAX 控件工具包是 ASP.NET 扩展程序控件的共享源码库。它最有用的一个控件是 ModalPopupExtender 控件,我在 2008 年 1 月的“领先技术安装”() 中对其进行了简要介绍。ModalPopup 扩展程序采用服务器端 ASP.NET 面板所生成的标记,并在用户单击关联的 HTML 元素时显示或隐藏此标记。对话框一开始是隐藏的,在加载页面时下载到客户端上,然后根据需要显示或隐藏。那么,模态是如何保证的呢?请看一下图 1 中的代码段。

Figure1ModalPopupExtender 控件的详细信息

// Code excerpted from modalpopupbehavior.js.
// Method initialize()
//
// Download the source code of the AJAX Control Toolkit from
// http://www.codeplex.com/atlascontroltoolkit.
//
// The panel defined as the popup is saved as the foreground element.
this._foregroundElement = this._popupElement;
// A new DIV tag is created as the background element for the panel.
// The panel is invisible and placed at 0,0 coordinates (fixed position).
// In addition, the background element is given a high z-index so that it
// sits above everything else.
this._backgroundElement = document.createElement("div");
this._backgroundElement.id = this.get_id() + "_backgroundElement";
this._backgroundElement.style.display = "none";
this._backgroundElement.style.position = "fixed";
this._backgroundElement.style.left = "0px";
this._backgroundElement.style.top = "0px";
this._backgroundElement.style.zIndex = 10000;
// The background element is styled as specified.
if (this._BackgroundCssClass)
{
this._backgroundElement.className = this._BackgroundCssClass;
}
// The background element is appended to the parent of the foreground
// element.
this._foregroundElement.parentNode.appendChild(this._backgroundElement);
// The foreground element is programmatically hidden from view. In
// addition, it is given absolute positioning and an higher z-index than
// the background element.
this._foregroundElement.style.display = "none";
this._foregroundElement.style.position = "fixed";
this._foregroundElement.style.zIndex = $common.getCurrentStyle(
this._backgroundElement, "zIndex", this._backgroundElement.style.zIndex) + 1;
// A click handler is added to the target element of the extender. In
// this case, It is the DOM element whose ID is passed on as the
// TargetControlID property.
this._showHandler = Function.createDelegate(this, this._onShow);
$addHandler(this.get_element(), "click", this._showHandler);

该代码显示用于在客户端上初始化 ModalPopup 扩展程序的脚本的摘录。请注意,ASP.NET AJAX 扩展程序通常包含一个服务器控件(扩展程序)和一个以 JavaScript 编写的客户端行为类。图 1 中的代码源自 ModalPopup 扩展程序的客户端行为类。如果您从 下载 AJAX 控件工具包的源代码,则会在 modalpopupbehavior.js 文件中发现上述代码。

如您在图 1 中所见,对话框标记树的根元素被指定为前台元素并以编程方式从视图中隐藏。同时,会动态创建一个 DIV 标记并将其指定为后台元素。该标记固定在坐标 0,0 处,并具有合适的样式。还为 DIV 标记提供了一个极高(但任意)的 z 索引,这实际上可确保该标记位于文档中所有其他元素之上,因为 z 索引属性设置 HTML 元素的堆栈顺序,而且堆栈顺序最高的元素始终显示在堆栈顺序较低的元素之上。