POST成功但数据未出现在控制器中[重复]

问题描述 投票:-1回答:2

这个问题在这里已有答案:

我试图将JSON数据发布到控制器。帖子成功但数据为空。

这是ajax代码:

$(document).ready(function () {
    var result = [];

    $.ajax({
        type: 'GET',
        url: 'https://api.ipdata.co/49.206.6.229?api-key=accesskey',
        success: function (data) {
            console.log(data.city),
            console.log(data.latitude),
            console.log(data.longitude),
            result= { "city": data.city, "latitude":data.latitude, "longitude":data.longitude };

            debugger
            $.ajax({
                contentType: 'application/json; charset=utf-8',
                datatype: 'JSON',
                type: 'POST',
                url: '/GeoLocation/GeoLocationData',
                data: result ,
                success: function (data) {
                    console.log(data),
                    alert('Post Successful');
                },
                error: function (data) {
                    alert('error');
                }  
            });
            debugger
        }
    });
});

我收到了Post Successful警报,但无法使用控制器中的数据。

这是我的控制器动作:

[HttpPost]
public ActionResult GeoLocationData(Location location)
{
    var city = location.city;
    var lat =  location.latitude;
    var lon =  location.longitude;
    return Ok();
}

我的型号:

public class Location
{
    public String city { get; set; }

    [Column("latitude")] 
    public double? latitude { get; set; }

    [Column("longitude")]
    public double? longitude { get; set; }
}

这是我从api获得的JSON数据:

data: { ...
   city: "xxxx", 
   continent_code: "xx" ,
   latitude: 17.3753, 
   longitude: 78.4744... }

当我检查调试器时,我可以看到数据正在正确传递,但是在第二个ajax调用中虽然我已经给出了

数据:结果

,数据需要

JSON响应值

。为什么会这样?

c# asp.net json ajax asp.net-core
2个回答
1
投票

您需要从正文中检索数据:

[HttpPost]
public ActionResult GeoLocationData([FromBody] Location location)

0
投票

在ajax请求上试试这个:

data: JSON.stringify(result),

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.