MVC 4:传递复杂对象异步控制器操作 [英] MVC 4: pass complex object to async controller action

查看:96
本文介绍了MVC 4:传递复杂对象异步控制器操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图至订单列表传递给使用Javascript一个异步控制器动作:

I'm trying to pass a list of orderlines to a async controller action using Javascript:

var model = "<some JSON string>";
$.ajax({ type: "POST",
  url: "/MyController/MyAction",
  datatype: "json",
  data: { 'orderLines': model},
  success: function(msg) {
     ...
  }
});

当我在运行时检查模型变量,OrderLine的属性值设置确定。但是,当我把一个断点在我的控制器动作,订单项目传入参数的属性都是0。它看起来像JSON字符串没有正确反序列化。

When I check the model variable in runtime, the values of the orderline properties are set ok. But when I put a breakpoint in my controller action, the properties of the orderline incoming parameter are 0. It looks like the JSON string wasn't properly deserialized.

控制器动作看起来是这样的:

The controller action looks like this:

public ActionResult AsyncUpdateOrderline(List<OrderLine> orderLines)
{
  ...
}

如何能正确地传递一个复杂的对象到一个异步控制器动作?

How can I correctly pass a complex object to a async controller action?

谢谢,
尼尔斯

Thanks, Nils

推荐答案

您需要设置请求Content-Type头,并使用 JSON.stringify 方法发送数据到控制器:

You need to set the request Content-Type header and also use the JSON.stringify method to send data to the controller:

var model = [
    { quantity: 1, name: 'some name 1' },
    { quantity: 2, name: 'some name 2' }
];

$.ajax({ 
    url: '/MyController/MyAction',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ orderLines: model }),
    success: function(msg) {
        ...
    }
});

注意模型应该怎么不是一个JSON字符串,但其中每个元素是反映你的订单行模型结构的JavaScript数组对象。

Notice how the model should not be a JSON string but a javascript array object where each element is reflecting the structure of your OrderLine model.

这篇关于MVC 4:传递复杂对象异步控制器操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆