我有一个数组,存储在<input type="hidden">中。这是我的代码。

Javascript:

var trees;

// called when the body loads
function BodyOnLoad()
{
  trees = document.getElementById("trees");
  trees.value = new Array();
}

// this is what isn't working
function AddTree()
{
  var i = trees.value.length;

  trees.value[i] = new Array();
  /***/
  trees.value[i]["branches"] = 5;
  trees.value[i]["trunk"]    = 0;
}

HTML:<input type="hidden" name="trees" id="trees" />
在C#中,Request.Form["trees"]不是数组。我究竟做错了什么?

最佳答案

HTML表单帖子不会保留javascript对象(在这种情况下为Array)。如果需要保留数组对象,应该查看将Array转换为JSON并将其传递给表单的情况。

在页面中包含此脚本(JSON2):
JSON2

var treesArray;

// called when the body loads
function BodyOnLoad()
{
  treesArray = new Array();
}

function AddTree()
{
  var tree = new Array();

  //branches
  tree[0] = "5";

  //trunk
  tree[1] = "0";

  //name
  tree[2] = "Elm";

  treesArray[treesArray.length] = tree;
  document.getElementById("trees").value = JSON.stringify(treesArray);
}

然后在服务器端,您将需要使用以下方法将JSON转换为C#数组:

从System.Web.Extensions.dll(.NET 3.5 SP1)添加对JavaScriptSerializer的引用
JavaScriptSerializer serializer = new JavaScriptSerializer();
string[][] trees = serializer.Deserialize<string[][]>(Request.Form["trees"]);

for(int i = 0; i < trees.Length; i++)
{
    Console.WriteLine("Branches:" + trees[i][0]);
    Console.WriteLine("Trunk:" + trees[i][1]);
    Console.WriteLine("Name:" + trees[i][2]);
}

10-06 15:43