我发现的其他一些事情:
您不能直接传入数组,例如:
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很好地涵盖了两者之间的差异。
这是我想出的完整示例:
// 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>