将ajax发送到控制器的问题

时间:2012-08-20 17:53:02

标签: ajax asp.net-mvc json asp.net-mvc-3 post

我有一个动作

[HttpPost]
    public JsonResult AddLocationsForOrder(List<BuyerOrderLocation> locations, string[] orders)
    {
        // something here
    }

和js代码,发送请求:

data = { locations: serializedLocations, orders: selector.val() };
     $.ajax({
            url: addLocationUrl,
            success: function (responseText) { Core.responceReceived(responseText, null, null); },
            error: function () { Core.showErrorNotification("Sorry, some error occured. Please contact administrator"); },
            async: false,
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(data)

        });

来自firebug的帖子详情如下:

locations


"[{"id":225,"country":"United States","countryShort":"US","state":"Iowa","stateShort":"IA","city":null,"zipCode":null,"address":"Douglas, IA, USA","latitude":41.9053851,"longtitude":-93.8349976,"bounds":null,"isDeleted":false,"county":"Boone","radius":0},{"id":226,"country":"United States","countryShort":"US","state":"Iowa","stateShort":"IA","city":null,"zipCode":null,"address":"Iowa, USA","latitude":41.8780025,"longtitude":-93.097702,"bounds":null,"isDeleted":false,"county":null,"radius":0}]"


orders


[ "10440" , "10441" , "10442" ]


0  "10440"


1  "10441"


2  "10442"

请求标题:

    Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-us,en;q=0.5
Connection  keep-alive
Content-Length  830
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
Cookie  ASP.NET_SessionId=ewtvgwleg5or1lqctinpjv2d; .ASPXAUTH=8414A94FE30B8F8D6FE862259398F39D6F6D2EE995C9EE16549987E2E1291851788CAB75425579F61F70EBE4C7B785B07CB36773894A5B2A513966247AA5B670A25D4AE565796B449912D745EBE5E5E4AB8280902C132FC3D97C0C33BA2C2357372CD9C9EA49983DC4A8E875C6E4D653FA049EC7B0F3824666F35D3838226AA19ACEEC1B8C5716E995966787268313FEF90E2ABBAE989CA682D406EBCE361BB7
Host    local.attorneyboost
Referer http://local.attorneyboost/Order/OrderInfo/10439
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1
X-Requested-With    XMLHttpRequest

正如您所看到的,请求类型是“POST”,我在发送到服务器之前“Jsoning”数据。但是在行动中我得到了参数的空值。我究竟做错了什么?我已经坚持寻找错误了

2 个答案:

答案 0 :(得分:1)

this文章中,他们解释了如何将复杂的JSON对象发送到ASP.NET。 希望这有帮助

答案 1 :(得分:1)

您需要在请求中指定数据类型,将其发送到服务器。被调用的datatype属性设置服务器响应的格式,以需要使用contentType属性发送到服务器的格式设置数据类型

修改使用此

调用的ajax
     $.ajax({
        url: addLocationUrl,
        success: function (responseText) { Core.responceReceived(responseText, null, null); },
        error: function () { Core.showErrorNotification("Sorry, some error occured. Please contact administrator"); },
        async: false,
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(data),
        contentType = 'application/json; charset=utf-8'
    });

您需要在请求中指定数据类型,将其发送到服务器。被调用的datatype属性设置服务器响应的格式,以需要使用contentType属性发送到服务器的格式设置数据类型