Dav*_*son 11 .net javascript c# asp.net code-behind
我想从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>
Run Code Online (Sandbox Code Playgroud)
并在后面的代码中:
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);
}
Run Code Online (Sandbox Code Playgroud)
有办法吗?
Dav*_*e L 10
如果您正在使用ScriptManager或任何Ajax控件/异步回发,请查看ScriptManager.RegisterStartupScript方法.
编辑:
实际上,您想要的功能可能是ScriptManager.RegisterClientScriptBlock
我发现的其他一些事情:
你不能直接传入一个数组,如:
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "xx",
"<script>test("+x+","+y+");</script>");
Run Code Online (Sandbox Code Playgroud)
因为它调用x和y的ToString()方法,返回"System.Int32 []",显然Javascript不能使用它.我必须将数组作为字符串传递,如"[1,2,3,4,5]",所以我编写了一个辅助方法来进行转换.
此外,this.Page.ClientScript.RegisterStartupScript()和this.Page.ClientScript.RegisterClientScriptBlock()之间存在差异 - 前者将脚本放在页面底部,这是我需要的,以便能够访问控件(与document.getElementByID一样).RegisterClientScriptBlock()在呈现标记之前执行,因此如果我使用该方法,实际上会出现Javascript错误.
这是我提出的完整示例:
// 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>
Run Code Online (Sandbox Code Playgroud)