将Ajax数据转换为MVC模型

时间:2014-04-24 22:20:16

标签: c# jquery asp.net-mvc

我们非常简单的模型:

public class OrderSubmissionProductViewModel
{
    public int Id { get; set; }
    public decimal Price { get; set; }
    public int Qty { get; set; }
}

public class OrderSubmissionViewModel
{
    public int CustomerId { get; set; }
    public int AccountId { get; set; }

    public OrderSubmissionProductViewModel[] Products { get; set; }
}

AJAX:

$.ajax({
    url: self.urlSubmitOrder,
    data: JSON.stringify({ submission: submission }),
    type: 'POST',
    success: function () { alert("Submitted"); },
    fail: function () { alert("Failed"); }
});

MVC控制器具有此方法签名:

public ActionResult SubmitAdminOrder(OrderSubmissionViewModel submission)
{ ... }

这就是POST的样子:

{"submission":{"CustomerId":43,"AccountId":"20000","Products":[{"Id":4,"Price":100,"Qty":1},{"Id":6,"Price":14,"Qty":1}]}}

我可以在控制器方法中遇到断点,并且模型不为null,但它的所有属性都是默认值。它没有被正确绑定。我究竟做错了什么?

我们正在使用ASP.Net MVC 4.

1 个答案:

答案 0 :(得分:1)

确保submission对象不是空的,您可以尝试在ajax选项中添加contentType吗?

$.ajax({
    url: self.urlSubmitOrder,
    data: JSON.stringify({ submission: submission }),
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    success: function () { alert("Submitted"); },
    fail: function () { alert("Failed"); }
});

或者看一下这篇文章Pass viewmodel with two objects to controller using Json