通过C#ASP.NET数组JavaScript数组 [英] Pass C# ASP.NET array to Javascript array

查看:303
本文介绍了通过C#ASP.NET数组JavaScript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何在C#ASP.NET数组传递给JavaScript数组?示例code也将是不错的。

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

现在我想通过数字到客户端,并在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注入的JavaScript插入的Page_Load页面。

You can use ClientScript.RegisterStartUpScript to inject javascript into the page on Page_Load.

下面是MSDN参考链接:
<一href=\"http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx\">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中的code:

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
}

这里有两个问题:

There's 2 problems here:


  1. 有些人认为这种侵入的C#注入的JavaScript

  1. Some consider this intrusive for C# to inject Javascript

我们将不得不阵列在全球范围内声明

We'll have to declare the array at a global context

如果你不能忍受这一点,另一种方法是将拥有C#code将数组保存到视图状态,然后有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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆