将多个对象数组从Javascript发布到MVC

时间:2012-10-05 14:16:45

标签: arrays json asp.net-mvc-3 posting

我找到了很多答案,可以将1个对象数组发布到MVC,但我正在努力解决多个问题。它可能是我失踪的小事。

这是我的JS:

 $.ajax({
                type: "POST",
                url: encodeURI("<%:Url.Action("SaveSimulator")%>"),
                data: JSON.stringify({ 
                    gevelshapes: (gevelshapes), 
                    gevelgaten:(gevelgaten),
                    dakshapes:(dakshapes),
                    dakgaten:(dakgaten),
                    dakrandshapes:(dakrandshapes), 
                    dakrandgaten:(dakrandgaten) 
                }),
                success: function(data){
                    $("form").submit();
                },
                contentType: 'application/json',
                dataType: "json"
            });

这些是包含具有x和y坐标的对象的数组。像这样:

var gevelshapes = [{ x: "1", y: "2" },{ x: "2", y: "1" }];

我的MVC控制器如下所示:

[HttpPost]
    public JsonResult SaveSimulator(List<Coordinaat> gevelshapes , List<Coordinaat> dakrandshapes, List<Coordinaat> dakshapes,List<Coordinaat> gevelgaten , List<Coordinaat> dakrandgaten, List<Coordinaat> dakgaten)
    {

        //do something 
    }

我错过了一些东西,因为MVC认为List<Coordinaat> gevelshapes有一个对象有一个空的x和y字符串而不是一个带有2&#39; coordinaat&#39;对象。

任何帮助都会很棒:)

1 个答案:

答案 0 :(得分:0)

也许我错了,但mvc不会自动解析Json字符串。试试这样:

 $.ajax({
            type: "POST",
            url: encodeURI("<%:Url.Action("SaveSimulator")%>"),
            data: { x : JSON.stringify({ 
                gevelshapes: (gevelshapes), 
                gevelgaten:(gevelgaten),
                dakshapes:(dakshapes),
                dakgaten:(dakgaten),
                dakrandshapes:(dakrandshapes), 
                dakrandgaten:(dakrandgaten) 
            }) },
            success: function(data){
                $("form").submit();
            },
            contentType: 'application/json',
            dataType: "json"
        });

[HttpPost]
public JsonResult SaveSimulator(string x)
{
     var serializer = new JavaScriptSerializer();
     var result = serializer.Deserialize<object>(x); // You can cast to your preffered class
     // ...
}