ASP.NET通过RegisterStartupScript执行客户端脚本

2015-01-18 18:10:44|?次阅读|上传:wustguangh【已有?条评论】发表评论

关键词:ASP.NET, Web, C#|来源:唯设编程网

用法:

public void Page_Load(Object sender, EventArgs e)
  {
    // Define the name and type of the client scripts on the page.
    String csname1 = "PopupScript";
    String csname2 = "ButtonClickScript";
    Type cstype = this.GetType();
        
    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;

    // Check to see if the startup script is already registered.
    if (!cs.IsStartupScriptRegistered(cstype, csname1))
    {
      String cstext1 = "alert('Hello World');";
      cs.RegisterStartupScript(cstype, csname1, cstext1, true);
    }

    // Check to see if the client script is already registered.
    if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
    {
      StringBuilder cstext2 = new StringBuilder();
      cstext2.Append("<script type="text/javascript"> function DoClick() {");
      cstext2.Append("Form1.Message.value='Text from client script.'} </");
      cstext2.Append("script>");
      cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
    }
  }

因为ClientScriptManager是一个密封类,密封类还和常规类一样的使用方法只是这个类没有构造函数,不能按照常规方法使用。可以使用下面的语句进行初始化

ClientScriptManager cs = Page.ClientScript; 

其它常用功能脚本:

1. 打开一个新窗口:

 cs.RegisterClientScriptBlock(cstype, csname2, 
    "<script language= 'javascript'>window.open('" + url + "','','toolbar=no,resizable=yes,scrollbars=yes')</script>",
    false);

2. 弹出警告窗口

// <summary>
// 服务器端弹出alert对话框
// </summary>
// <param name="str_message">提示信息,例子:"不能为空!"</param>
// <param name="page">page类</param>
public void alert(string str_message,page page)
{
    cs.RegisterClientScriptBlock(cstype, csname2,
        "<script>alert('"+str_message+"');</script>", 
        false);
}

3. 重载此警告窗口,使某控件获得焦点

// <summary>
// 服务器端弹出alert对话框,并使控件获得焦点
// </summary>
// <param name="str_ctl_name">获得焦点控件id值,比如:txt_name</param>
// <param name="str_message">提示信息,例子:"请输入您姓名!"</param>
// <param name="page">page类</param>
public void alert(string str_ctl_name,string str_message,page page)
{
    cs.RegisterClientScriptBlock(cstype, csname2,
        "<script>alert('"+str_message+"');document.forms(0)."+str_ctl_name+".focus(); document.forms(0)."+str_ctl_name+".select();</script>",
         false);
}
发表评论0条 】
网友评论(共?条评论)..
ASP.NET通过RegisterStartupScript执行客户端脚本