客户端脚本管理

在 ASP.NET 1.x 中编写需要自定义资源(如图像或客户端脚本)的自定义控件的开发人员需要在 aspnet_client 虚拟文件夹中安装这些资源。在 ASP.NET 2.0 中,可利用 Web 资源简化此过程。Web 资源允许将资源嵌入程序集中,并通过 Web 资源处理程序进行检索。下面的示例演示嵌入的 JavaScript 文件的用法,以及 Page.ClientScript.RegisterClientScriptResource 方法的用法。如果嵌入的是样式表,则需要考虑注册样式表并使用 Page.ClientScript.GetWebResourceUrl 指向嵌入的资源。

 
// Mark the assembly with the resource
[assembly: WebResource("CustonmControlScript.js", "text/javascript")]

public class CustomControl : WebControl {
 
  // Additional implementation

  protected override void OnPreRender(EventArgs e) {
    this.Page.ClientScript.RegisterClientScriptResource(typeof(CustomControl), "CustomControlScript.js");
    this.Attributes.Add("onmouseover", "MouseOverScript()");
    base.OnPreRender(e);
  }
}

 

Control.Page 属性公开一个封装了处理、注册和引用客户端脚本功能的 ClientScript 属性。当与 Web 资源组合时,您同样可以将那些脚本嵌入到控件的程序集中,请参见 Web 资源中的示例

 
public class MyButton : Button {
  protected override void OnPreRender(EventArgs e) {
    String sScript = "function DoAlert(){alert('Hello World');}";
    this.Page.ClientScript.RegisterClientScriptBlock(typeof(MyButton),
      "ScriptFunction", sScript, true);

    OnClientClick = "javascript:DoAlert();";
    base.OnPreRender(e);
  }

  // Additional implementation

}

 
posted @ 2006-11-13 12:44  永春  阅读(418)  评论(0编辑  收藏  举报