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

时间:2012-09-01 16:39:37

标签: 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] = 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。谁能告诉我这个问题?

2 个答案:

答案 0 :(得分:1)

您必须使用JSON来执行此操作。根据{{​​1}}类的实际代码,这将在Javascript方面为您提供类似的内容:

Constructor

是具有属性[{"foo":"A", "bar":"B"}, {"foo":"C", "bar":"D"}] foo的2个对象的数组的JSON表示。

在服务器端,您必须将JSON结构转换回实际的对象结构。当然有图书馆(我不是C#家伙,所以我不知道)

答案 1 :(得分:0)

如果您正在使用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;
}