ASP.NET后台输出js的三种方式(写给初学者)

ASP.NET提供了三种后台输出JS的方式:

一、后台输出已有js文件

首先创建 js文件testjs.js

if (!Page.ClientScript.IsClientScriptIncludeRegistered(this.GetType(), "keys"))//判断keys是否已注册过
{
   Page.ClientScript.RegisterClientScriptInclude("keys", "testjs.js");     

二、输出js代码块

string scriptstrs = "";//此处只作为演示,如代码需多次拼接应采用StringBuilder方式
scriptstrs += "function test(str)";
scriptstrs+="{alert(str);}";
if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "keys"))

     Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "keys", scriptstrs, true);

}

三、 输出一次性使用的js代码

        string scriptstrs = "<script>alert('欢迎光临!');</script>";
        if (!Page.ClientScript.IsStartupScriptRegistered(this.GetType(),"welcome"))
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "welcome", scriptstrs);
        }

此外,运用Response.Write("<script>alert('ww');</script>"); 方式也可输出简单js代码,但我个人不提倡采用此种方式。因为在以前开发中遇到有些情况下此种方式会导致弹出提示信息后页面字号改变的现象,所以安全起见建议采用上述三种方式。

原文地址:https://www.cnblogs.com/zxh0208/p/1775533.html