Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将对象数组从javascript传递到服务器_C#_Javascript_Jquery_Asp.net Mvc 3 - Fatal编程技术网

C# 如何将对象数组从javascript传递到服务器

C# 如何将对象数组从javascript传递到服务器,c#,javascript,jquery,asp.net-mvc-3,C#,Javascript,Jquery,Asp.net Mvc 3,我正在从javascript向MVC控制器进行ajax调用,将对象数组传递给控制器操作 Js代码: function Constructor(p1, p2) { this.foo = p1; this.bar = p2; } var Obejct_Array = new Array(); Obejct_Array[Obejct_Array.length] = new Constructor("A", "B"); Obejct_Array[Obejct_Array.length

我正在从javascript向MVC控制器进行ajax调用,将对象数组传递给控制器操作

Js代码:

function Constructor(p1, p2) {
    this.foo = p1;
    this.bar = p2;
}

var Obejct_Array = new Array();

Obejct_Array[Obejct_Array.length] = new Constructor("A", "B");
Obejct_Array[Obejct_Array.length] = new Constructor("C", "D");

$.post("/_Controller/_Action", { ObjectArray : Obejct_Array });
C#代码

public Class Example
{
  public string foo { get; set; }
  public string bar { get; set; }
  public string Prop3 { get; set; }
}

 //Action in Controller
 public void _Action(Example[] ObejctArray)
 {
  //Here the size of ObjectArray is 2 but the properties are all null. Whats the problem ?
 }
javascript数组中的两个条目都将传递给控制器的操作方法,但属性值显示为null。有谁能告诉我这个问题吗?

你必须用它来做这件事。根据
构造函数的实际代码,这将在Javascript端为您提供如下内容:

[{"foo":"A", "bar":"B"}, {"foo":"C", "bar":"D"}]
这是一个包含两个对象的数组的JSON表示,其属性分别为
foo
bar


在服务器端,必须将JSON结构转换回实际的对象结构。当然有这样的库(我不是C#guy,所以我不知道任何库)

如果您使用的是MVC,您可以传递数组数据,以便它将直接绑定到动作方法中的数组参数。MVC预计数据如下:

// in js
var data = {
    // could also put the name of the parameter before each [0/1] index
    "[0].foo": "A",
    "[0].bar": "B",
    "[1].foo": "C",
    "[1].bar": "D"
};

// a js function to put the data in this format:
function (array, prefix) {
    var prefixToUse = prefix || "",
        data = {},
        i, key;
    for (i = 0; i < array.length; i++) {
        for (key in array[i]) {
            // might want to do some filtering here depending on what properties your objects have
            data[prefixToUse + "[" + i + "]." + key] = array[i][key];
        }
    }

    return data;
}
//在js中
风险值数据={
//也可以将参数名称放在每个[0/1]索引之前
[0].foo:“A”,
[0]。条“:“B”,
“[1].foo”:“C”,
[1]。条形图:“D”
};
//一个js函数,用于以这种格式放置数据:
函数(数组、前缀){
var prefixToUse=前缀| |“”,
数据={},
i、 钥匙;
对于(i=0;i
C#中要使用的库是JSON.net(),将其字符串化,并在服务器端将其转换回来@adeneo能否请你给出一个示例代码不确定你是如何在C#中实现的,但是Lee Taylor已经在下面发布了一个链接。在javascript中,您可以执行
JSON.stringify(Obejct_Array)
,我认为您希望它是一个字符串,因为它是一个数组和所有数组,只需将其转换回服务器即可。