简体   繁体   English

从代码隐藏中传递JavaScript函数的参数

[英]Passing arguments to JavaScript function from code-behind

I would like to call a javascript function from an aspx control. 我想从aspx控件调用一个javascript函数。 For instance, suppose I had: 例如,假设我有:

<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? 有办法吗?

Look at the ScriptManager.RegisterStartupScript method 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

您可以使用Page.ClientScript.RegisterStartupScript方法。

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. 因为它调用x和y的ToString()方法,返回“System.Int32 []”,显然Javascript不能使用它。 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. 我必须将数组作为字符串传递,如“[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). 此外,this.Page.ClientScript.RegisterStartupScript()和this.Page.ClientScript.RegisterClientScriptBlock()之间存在差异 - 前者将脚本放在页面底部,这是我需要的,以便能够访问控件(与document.getElementByID一样)。 RegisterClientScriptBlock() is executed before the tags are rendered, so I actually get a Javascript error if I use that method. RegisterClientScriptBlock()在呈现标记之前执行,因此如果我使用该方法,实际上会出现Javascript错误。

http://www.wrox.com/WileyCDA/Section/Manipulating-ASP-NET-Pages-and-Server-Controls-with-JavaScript.id-310803.html covers 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>

include script manager 包括脚本管理器

code behind function 代码背后的功能

ScriptManager.RegisterStartupScript(this, this.GetType(), "HideConfirmBox", "javascript:HideAAConfirmBox(); ", true);
Response.Write("<scrip" + "t>test(" + x + "," + y + ");</script>");

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

<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 cs代码

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

try this 尝试这个

 <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;
}

If you are interested in processing Javascript on the server , there is a new open source library called Jint that allows you to execute server side Javascript. 如果您对在服务器上处理Javascript感兴趣,可以使用一个名为Jint的新开源库,它允许您执行服务器端Javascript。 Basically it is a Javascript interpreter written in C#. 基本上它是一个用C#编写的Javascript解释器。 I have been testing it and so far it looks quite promising. 我一直在测试它,到目前为止看起来很有希望。

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. Jint是不同的,因为它不使用CodeDomProvider技术,它使用引擎盖下的编译,因此导致内存泄漏,因为编译的程序集无法卸载。 Moreover, using this technique prevents using dynamically types variables the way JavaScript does, allowing more flexibility in your scripts. 此外,使用此技术可防止像JavaScript一样使用动态类型变量,从而在脚本中提供更大的灵活性。 On the opposite, Jint embeds it's own parsing logic, and really interprets the scripts. 相反,Jint嵌入了它自己的解析逻辑,并且真正解释了脚本。 Jint uses the famous ANTLR ( http://www.antlr.org ) library for this purpose. 为此,Jint使用着名的ANTLR( http://www.antlr.org )库。 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. 由于它使用Javascript作为其语言,您不必学习新语言,它已被证明对于脚本编写非常强大,您可以使用多个文本编辑器进行语法检查。

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>");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM