我发现的一些其他事情:
你不能直接传递一个数组,例如:
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "xx",
"<script>test("+x+","+y+");</script>");
因为调用了x和y的ToString()方法,返回"System.Int32[]",显然Javascript无法使用。我不得不将数组作为字符串传递,例如"[1,2,3,4,5]",因此我编写了一个帮助方法来进行转换。
此外,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.html很好地介绍了两者之间的区别。
以下是我想到的完整示例:
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);
string yStr = getArrayString(y);
string script = String.Format("test({0},{1})", xStr, yStr);
this.Page.ClientScript.RegisterStartupScript(this.GetType(),
"testFunction", script, true);
}
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;
}
<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];
}
text1.innerText += "\ny: " + y;
}
</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>