JS与ASP.NET间传值

一. JS中取得Asp.Net的值
(1)取得服务端控件的值
var s = document.getElementById("TextBox1").value;   //取得TextBox1的Text值
(2)取得全局变量的值
在Page_Load()方法前定义protected String sT;
在Page_Load()方法中赋值sT = "哈哈";
JS中这样写取得
var s = "<%=sT %>";
--------------------------------------------------------------------------------
二. Asp.Net中取得JS的值
推荐使用<asp:HiddenField ID="HiddenField1" runat="server" />控件
在JS中添加代码
document.getElementById("HiddenField1").value = '风中追风';
在后台代码中,可以直接使用HiddenField1.Value取得
使用<input type="hidden" id="leslie" runat="server" />
在后台代码中,可以直接使用leslie.Value取得
PS:
也可以使用<input type="hidden" id="leslie" name="leslie">方法
在后台操作中用Request.Form.Get("leslie");  //取得的是name="leslie"的值 ......

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

1.后台输出已有js文件

首先创建 js文件testjs.js

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

2.输出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);

}

3. 输出一次性使用的js代码

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

原文地址:https://www.cnblogs.com/wangrsh2010/p/1900877.html