C# 从代码隐藏向 JavaScript 函数传递参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/788330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:13:05  来源:igfitidea点击:

Passing arguments to JavaScript function from code-behind

c#javascript.netasp.netcode-behind

提问by David Hodgson

I would like to call a javascript function from an aspx control. For instance, suppose I had:

我想从 aspx 控件调用 javascript 函数。例如,假设我有:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
    function test(x, y)
    {

    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button"
         onclick="Button1_Click"/>
    </div>
    </form>
</body>
</html>

and in the code behind:

并在后面的代码中:

protected void Button1_Click(object sender, EventArgs e)
{
    // do stuff (really going to a database to fill x and y)
    int[] x = new int[] { 1, 2, 3, 4, 5 };
    int[] y = new int[] { 1, 2, 3, 4, 5 };

    // call javascript function as test(x,y);
}

Is there a way to do it?

有没有办做到这一点?

采纳答案by Kirtan

回答by Dave L

Look at the ScriptManager.RegisterStartupScriptmethod if you're using a ScriptManager or any Ajax controls/asynchronous postbacks.

如果您使用的是 ScriptManager 或任何 Ajax 控件/异步回发,请查看ScriptManager.RegisterStartupScript方。

Edit:

编辑:

Actually, the function you want is probably ScriptManager.RegisterClientScriptBlock

其实你想要的函数大概是ScriptManager.RegisterClientScriptBlock

回答by Thomas Stock

I think you want to execute the javascript serverside and not in the browser after post-back, right?

我认为您想在回发后执行 javascript 服务器端而不是在浏览器中,对吗?

That's not possible as far as I know

据我所知这是不可能的

If you just want to get it execute after postback, you can do something like this:

如果您只想在回发后执行它,您可以执行以下操作:

this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "xx", "<script>test("+x+","+y+");</script>");

回答by Chad Grant

Response.Write("<scrip" + "t>test(" + x + "," + y + ");</script>");

breaking up the script keyword because VStudio / asp.net compiler doesn't like it

分解脚本关键字,因为 VStudio / asp.net 编译器不喜欢它

回答by David Hodgson

Some other things I found out:

我发现的其他一些事情:

You can't directly pass in an array like:

你不能直接传入一个数组,如:

this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "xx",   
"<script>test("+x+","+y+");</script>");

because that calls the ToString() methods of x and y, which returns "System.Int32[]", and obviously Javascript can't use that. I had to pass in the arrays as strings, like "[1,2,3,4,5]", so I wrote a helper method to do the conversion.

因为它调用了 x 和 y 的 ToString() 方,它返回“System.Int32[]”,显然 Javascript 不能使用它。我必须将数组作为字符串传递,例如“[1,2,3,4,5]”,因此我编写了一个辅助方来进行转换。

Also, there is a difference between this.Page.ClientScript.RegisterStartupScript() and this.Page.ClientScript.RegisterClientScriptBlock() - the former places the script at the bottom of the page, which I need in order to be able to access the controls (like with document.getElementByID). RegisterClientScriptBlock() is executed before the tags are rendered, so I actually get a Javascript error if I use that method.

此外,this.Page.ClientScript.RegisterStartupScript() 和 this.Page.ClientScript.RegisterClientScriptBlock() 之间也有区别 - 前者将脚本放在页面底部,我需要它才能访问控件(与 document.getElementByID 类似)。RegisterClientScriptBlock() 在标记呈现之前执行,因此如果我使用该方,我实际上会收到 Javascript 错误。

http://www.wrox.com/WileyCDA/Section/Manipulating-ASP-NET-Pages-and-Server-Controls-with-JavaScript.id-310803.htmlcovers the difference between the two pretty well.

http://www.wrox.com/WileyCDA/Section/Manipulating-ASP-NET-Pages-and-Server-Controls-with-JavaScript.id-310803.html很好地涵盖了两者之间的区别。

Here's the complete example I came up with:

这是我想出的完整示例:

// code behind
protected void Button1_Click(object sender, EventArgs e)
{
    int[] x = new int[] { 1, 2, 3, 4, 5 };
    int[] y = new int[] { 1, 2, 3, 4, 5 };

    string xStr = getArrayString(x); // converts {1,2,3,4,5} to [1,2,3,4,5]
    string yStr = getArrayString(y);

    string script = String.Format("test({0},{1})", xStr, yStr);
    this.Page.ClientScript.RegisterStartupScript(this.GetType(),
    "testFunction", script, true);
    //this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
    //"testFunction", script, true); // different result
}
private string getArrayString(int[] array)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < array.Length; i++)
    {
        sb.Append(array[i] + ",");
    }
    string arrayStr = string.Format("[{0}]", sb.ToString().TrimEnd(','));
    return arrayStr;
}

//aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
    function test(x, y)
    {
        var text1 = document.getElementById("text1")
        for(var i = 0; i<x.length; i++)
        {
            text1.innerText += x[i]; // prints 12345
        }
        text1.innerText += "\ny: " + y; // prints y: 1,2,3,4,5

    }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button"
         onclick="Button1_Click" />
    </div>
    <div id ="text1"> 
    </div>
    </form>
</body>
</html>

回答by David Robbins

If you are interested in processing Javascript on the server, there is a new open source library called Jintthat allows you to execute server side Javascript. Basically it is a Javascript interpreter written in C#. I have been testing it and so far it looks quite promising.

如果您对在服务器上处理 Javascript 感兴趣,有一个名为Jint的新开源库可以让您执行服务器端 Javascript。基本上它是一个用 C# 编写的 Javascript 解释器。我一直在测试它,到目前为止它看起来很有希望。

Here's the description from the site:

以下是该网站的描述:

Differences with other script engines:

Jint is different as it doesn't use CodeDomProvider technique which is using compilation under the hood and thus leads to memory leaks as the compiled assemblies can't be unloaded. Moreover, using this technique prevents using dynamically types variables the way JavaScript does, allowing more flexibility in your scripts. On the opposite, Jint embeds it's own parsing logic, and really interprets the scripts. Jint uses the famous ANTLR (http://www.antlr.org) library for this purpose. As it uses Javascript as its language you don't have to learn a new language, it has proven to be very powerful for scripting purposes, and you can use several text editors for syntax checking.

与其他脚本引擎的区别:

Jint 是不同的,因为它不使用 CodeDomProvider 技术,该技术在引擎盖下使用编译,因此由于无卸载编译的程序集而导致内存泄漏。此外,使用这种技术可以防止像 JavaScript 那样使用动态类型变量,从而使您的脚本具有更大的灵活性。相反,Jint 嵌入了它自己的解析逻辑,并真正解释了脚本。为此,Jint 使用了著名的 ANTLR ( http://www.antlr.org) 库。由于它使用 Javascript 作为其语言,因此您无需学习新语言,事实证明它非常强大,可用于脚本目的,并且您可以使用多个文本编辑器进行语检查。

回答by sunny

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call java script function on Code behind</title>
    <script  type="text/javascript">
    function abc()
    {
        var a=20;
        var b=30;
        alert("you enter"+a+":"+b);
    }
    </script>
</head>

cs code

代码

protected void Page_Load(object sender, EventArgs e)
{
    TextBox2.Attributes.Add("onkeypress", "return abc();");
}

try this

尝试这个

回答by Sai Sherlekar

include script manager

包括脚本管理器

code behind function

函数背后的代码

ScriptManager.RegisterStartupScript(this, this.GetType(), "HideConfirmBox", "javascript:HideAAConfirmBox(); ", true);

回答by Bhushan Mahajan

 <head>
    <script type="text/javascript">

        function test(x, y) 
        {
            var cc = "";
            for (var i = 0; i < x.length; i++) 
            {
                cc += x[i]; 
            }
            cc += "\ny: " + y; 
            return cc;
        }

    </script>



</head>

<body>

    <form id="form1" runat="server">

        <asp:Button ID="Button1" runat="server" Text="Button"   />

        <p>
             <asp:TextBox ID="TextBox1"  Name="TextBox1"  runat="server" AutoPostBack="True"  TextMode="MultiLine"></asp:TextBox>
        </p>



    </form>
</body>

protected void Page_Load(object sender, EventArgs e)
{
    int[] x = new int[] { 1, 2, 3, 4, 5 };
    int[] y = new int[] { 1, 2, 3, 4, 5 };

    string xStr = getArrayString(x); // converts {1,2,3,4,5} to [1,2,3,4,5]
    string yStr = getArrayString(y);

    string script = String.Format(" var y = test({0},{1}) ; ", xStr, yStr);
    script += String.Format("  document.getElementById(\"TextBox1\").value = y  ");

    this.Page.ClientScript.RegisterStartupScript(this.GetType(),  "testFunction", script, true);
  //  this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "testFunction", script, true); // different result
}




private string getArrayString(int[] array)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < array.Length; i++)
    {
        sb.Append(array[i] + ",");
    }
    string arrayStr = string.Format("[{0}]", sb.ToString().TrimEnd(','));
    return arrayStr;
}