【问题标题】:POST successful but the data doesn't appear in the controller [duplicate]POST成功,但数据没有出现在控制器中[重复]
【发布时间】:2018-10-10 13:08:49
【问题描述】:

我正在尝试将 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 Success 警报,但无法使用控制器中的数据。

这是我的控制器动作:

[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 响应值

。为什么会这样?

【问题讨论】:

  • GeoLocationData 不返回数据。只有 HTTP STATUS 200 OK
  • 尝试使用这个 class=> public class Location { public string city { get; set; } public string continent_code { get; set; } public double latitude { get; set; } public double longitude { get; set; } }
  • @Nkosi 我在控制器中返回 JSON 结果,仍然面临同样的问题。然后我更改为状态 ok 但问题仍然存在:)。

标签: c# asp.net json ajax asp.net-core


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    在 ajax 请求上试试这个:

    data: JSON.stringify(result),
    

    希望这会有所帮助!

    【讨论】:

    • 以上方法都试过了,还是一样的问题,所以改回来了!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    相关资源
    最近更新 更多