gpt4 book ai didi

c# - 通过表单将变量从 Javascript 传递到 C#?

转载 作者:行者123 更新时间:2023-11-29 10:23:12 24 4
gpt4 key购买 nike

我有一个存储在 <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 对象(在本例中为数组)。如果您需要保留数组对象,您应该考虑将数组转换为 JSON 并在表单中传递 that

在您的页面中包含此脚本 (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]);
}

关于c# - 通过表单将变量从 Javascript 传递到 C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7264535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com