将复杂JSON对象传递给MVC 3操作

时间:2012-03-07 22:36:32

标签: json asp.net-mvc-3

尝试将复杂的JSON对象传递给MVC 3中的操作时,我得到了一些奇怪的结果。

Locations填充在动作参数模型上,但名称和位置不是。

如果我ko.toJS(testViewModel),那么名称和位置就在那里,但位置是空白的???

我正在使用knockout.js:

var testViewModel = {
        Name: ko.observable("Joe Bob"),
        Locations: ko.observableArray([
            { ID: 1, Name: "Salem, OR" },
            { ID: 2, Name: "Big Bear Lake, CA" },
            { ID: 3, Name: "Big Bear City, CA" }
        ]),
        Position: ko.observable("Manager")
    }

通过jQuery ajax发送:

$.ajax({
            url: "/ClaimsAuthority/Home/TestIt",
            type: "POST",
            data: ko.toJSON(testViewModel),
            success: function (data, status, xhr) {
                //ko.applyBindings(data);
            }
        });

MVC行动:

<HttpPost()>
        Public Function TestIt(model As TestModel) As ActionResult
            Return Json(model)
        End Function

型号:

Public Class TestModel 
    Public Property ID As Integer
    Public Property Name As String
    Public Property Locations As ICollection(Of LocationModel)
    Public Property Position As String  
End Class

Public Class LocationModel
    Public Property ID As Integer
    Public Property Name As String
    Public ReadOnly Property DisplayText As String
        Get
            Return String.Format("({0}) {1}", ID, Name)
        End Get
    End Property
End Class

1 个答案:

答案 0 :(得分:15)

尝试在AJAX请求中将内容类型设置为application/json

$.ajax({
    url: '/ClaimsAuthority/Home/TestIt',
    type: 'POST',
    contentType: 'application/json',
    data: ko.toJSON(testViewModel),
    success: function (data, status, xhr) {
        //ko.applyBindings(data);
    }
});
相关问题