js将复杂对象发布到asp.net mvc

时间:2018-04-26 03:50:26

标签: javascript asp.net-mvc-3

js中的数据格式如下:

var data = {};
data = {
  orderInfo: {
   time: '2018-04-01',
   phone: '111122223333'
  },
  products: [
  {id: 1, count: 1},
  {id: 2, count: 2} 
  ]
}

然而,当我使用jQuery的ajax()方法直接发布时,后端无法接收我发布的内容,但是当以下面的格式发布时:

var data = {};
data['orderInfo.time'] = '2018-04-01';
data['orderInfo.phone'] = 111122223333;
data['products[0].id'] = 1;
data['products[0].count'] = 1;
data['products[1].id'] = 2;
data['products[1].count'] = 2;

后端可以接收数据,是什么造成的?任何帮助都会感激不尽。 ajax代码:

    $.ajax({
        type: 'POST',
        data: data,
        url: '/SaveOrderInfo'
    }).done(function (data, status, request) {

    }).fail(function (err) {

    });

简化的后端代码

namespace balabala {
    [DataContract]
    public class RVOrderViewRqst : IExtensibleDataObject
    {
        public ExtensionDataObject ExtensionData { get; set; }

        [DataMember]
        public RVOrderCustom orderInfo { get; set; }

        [DataMember]
        public IList < RVOrderDetailCustom > products { get; set; }


        public RVOrderViewRqst()
        {
            products = new List<RVOrderDetailCustom>();
        }
    }

    [DataContract]
    public class OrderDetailInfoCustom {
        [DataMember]
        public RVOrderCustom orderInfo { get; set; }

    [DataMember]
        public IList < RVOrderDetailCustom > products { get; set; }

        public OrderDetailInfoCustom()
    {
        products = new List<RVOrderDetailCustom>();
    }
}

[DataContract]
public class RVOrderDetailCustom {
[DataMember]
        public int id { get; set; }
[DataMember]
        public int count { get; set; }
    }

[DataContract]
public class RVOrderCustom {
    [DataMember]
[DataMember]
        public string time { get; set; }
[DataMember]
        public string phone { get; set; }
    }
}

让我理解变得复杂,后端老兄找不到原因。

2 个答案:

答案 0 :(得分:0)

尝试添加dataType: 'json'

$.ajax({
        type: 'POST',
        data: data,
        url: '/SaveOrderInfo',
        dataType: 'json'
    }).done(function (data, status, request) {

    }).fail(function (err) {

    });

你还需要在BE中设置像

这样的标题

Response.ContentType = "application/json";

Response.Headers.Add("Content-type", "application/json");

答案 1 :(得分:0)

尝试将dataType选项添加到ajax调用。

dataType: 'json'