0

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

This is the ajax code:

$(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.

This is my controller Action :

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

My Model:

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

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

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

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

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

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

data : result

, data takes the

JSON response value

. Why is this so?

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
  • `GeoLocationData` does not return data. only HTTP STATUS 200 OK – Nkosi Oct 10 '18 at 13:13
  • try to use this 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; } }` – er-sho Oct 10 '18 at 13:15
  • @Nkosi I was returning with the JSON result in the controller, still faced the same problem. Then I changed to status ok but the problem persists:). – Abhilash Gopalakrishna Oct 10 '18 at 13:38

2 Answers2

2

You need to retrieve data from body :

[HttpPost]
public ActionResult GeoLocationData([FromBody] Location location)
agua from mars
  • 16,428
  • 4
  • 61
  • 70
0

On ajax request try this:

data: JSON.stringify(result),

Hope this helps!

Deivid Carvalho
  • 311
  • 2
  • 12