从jquery ajax将复杂对象传递给asp.net MVC中的Action

时间:2011-11-18 00:03:51

标签: asp.net-mvc-3 jquery

我定义了以下域模型:

    public class myModel {
       public string Prop1 {get;set;}
       public string Prop2 {get;set;}
       public List<myClass> ListofStuff {get;set;}        
    }


    public myClass {
       public string Id{get;set;}
       public string Name{get;set;}
    }

然后我将控制器动作定义如下:

 [HttpPost]
    public ActionResult Save(MyModel someModel )
    {
      //do the saving
    }

我使用jquery ajax

从我的JS代码中调用上述操作
var someModel = {  Prop1: "somevalue1",
                   Prop2: "someothervalue",
                   ListofStuff: [{Id: "11", Name:"Johnny"}, {Id:"22", Name:"Jamie"}]

           };    

 $.ajax({
        contentType: 'application/json, charset=utf-8',
        type: "POST",
        url: "/myController/Save",
        data: JSON.stringify({someModel: someModel}),
        cache: false,
        dataType: "json",

        success: function () {

            alert('success!');
        },

        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert('error');            
        }

    });

EDITED: 当我运行上面的代码时,我得到错误处理程序执行。我试图安装Firebug,但我的FF是版本8,它无法安装它。所以我不确定错误是什么或如何看待它是什么。

我做错了什么?

2 个答案:

答案 0 :(得分:3)

我解决了这个问题。 MyClass需要具有无参数构造函数才能使绑定正常工作。希望这有助于某人。

答案 1 :(得分:2)

您可以使用以下方法。

$.postifyData = function (value) {
var result = {};

var buildResult = function (object, prefix) {
    for (var key in object) {

        var postKey = isFinite(key)
            ? (prefix != "" ? prefix : "") + "[" + key + "]"
            : (prefix != "" ? prefix + "." : "") + key;

        switch (typeof (object[key])) {
            case "number": case "string": case "boolean":
                result[postKey] = object[key];
                break;

            case "object":
                if (object[key] != null) {
                    if (object[key].toUTCString) result[postKey] = object[key].toUTCString().replace("UTC", "GMT");
                    else buildResult(object[key], postKey != "" ? postKey : key);
                }
        }
    }
};

buildResult(value, "");
return result;
}

之后你可以传递像。的模型。

var someModel = new Object();
        someModel.Prop1 = "Pp1";
        someModel.Prop2 = "PP2";
        someModel.ListofStuff = new Array();
        //Use for each loop to bind list  like
        for (var i = 0; i < 2; i++) {
            var childObj = new Object();
            childObj.Id = "123" + i;
            childObj.Name = "Pankaj"
            someModel.ListofStuff.push(childObj);
        }
        $.ajax({
            type: "POST",
            url: "/home/test",
            data: $.postifyData(someModel),
            cache: false,
            dataType: "json",

            success: function () {

                alert('success!');
            },

            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('error');
            }

        });

我自己检查过,这样做很好。