将 C# ASP.NET 数组传递给 Javascript 数组 [英] Pass C# ASP.NET array to Javascript array
问题描述
有谁知道如何将 C# ASP.NET 数组传递给 JavaScript 数组?示例代码也很好.
Does anyone know how to pass a C# ASP.NET array to a JavaScript array? Sample code will also be nice.
对不起,如果我之前的人含糊不清.这个问题其实很简单.为简单起见,让我们在我的 aspx.cs
文件中声明:
Sorry if I was vague earlier guys. The question is actually quite simple. Let's say for simplicity that in my aspx.cs
file I declare:
int [] numbers = new int[5];
现在我想将 numbers
传递给客户端并在 JavaScript 中使用数组中的数据.我该怎么做?
Now I want to pass numbers
to the client side and use the data in the array within JavaScript . How would I do this?
推荐答案
您可以使用 ClientScript.RegisterStartUpScript 在 Page_Load 上将 javascript 注入页面.
You can use ClientScript.RegisterStartUpScript to inject javascript into the page on Page_Load.
这是 MSDN 参考的链接:http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx
Here's a link to MSDN reference: http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx
这是 Page_Load 中的代码:
Here's the code in Page_Load:
List<string> tempString = new List<string>();
tempString.Add("Hello");
tempString.Add("World");
StringBuilder sb = new StringBuilder();
sb.Append("<script>");
sb.Append("var testArray = new Array;");
foreach(string str in tempString)
{
sb.Append("testArray.push('" + str + "');");
}
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "TestArrayScript", sb.ToString());
注意:使用 StringBuilder 构建脚本字符串,因为它可能很长.
Notes: Use StringBuilder to build the script string as it will probably be long.
这是在您可以使用它之前检查注入的数组testArray"的Javascript:
And here's the Javascript that checks for the injected array "testArray" before you can work with it:
if (testArray)
{
// do something with testArray
}
这里有两个问题:
有些人认为这会妨碍 C# 注入 Javascript
Some consider this intrusive for C# to inject Javascript
我们必须在全局上下文中声明数组
We'll have to declare the array at a global context
如果您不能忍受,另一种方法是让 C# 代码将数组保存到视图状态,然后让 JavaScript 使用 PageMethods(或 Web 服务)回调服务器以获取该视图状态对象作为数组.但我认为对于这样的事情来说这可能有点矫枉过正.
If you can't live with that, another way would be to have the C# code save the Array into View State, then have the JavaScript use PageMethods (or web services) to call back to the server to get that View State object as an array. But I think that may be overkill for something like this.
这篇关于将 C# ASP.NET 数组传递给 Javascript 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!