POST成功,但数据未出现在控制器中 [英] POST successful but the data doesn't appear in the controller

查看:38
本文介绍了POST成功,但数据未出现在控制器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将JSON数据发布到控制器.发布成功,但数据为空.

I am trying to post JSON data to the controller. The post is successful but the data is null.

这是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
        }
    });
});

我收到发布成功"警报,但无法使用控制器中的数据.

I am getting the Post Successful alert, but am not able to use the data in the controller.

这是我的控制器操作:

[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数据:

This is the JSON data I am getting from the api:

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

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

When I inspect the debugger, I can see that the data is being passed correctly, however in the second ajax call though I have given

数据:结果

,数据占用

JSON响应值

JSON response value

.为什么会这样?

推荐答案

您需要从body检索数据:

You need to retrieve data from body :

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

这篇关于POST成功,但数据未出现在控制器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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