JSON-data get undefined as result. How to get JSON-data?

Viewed 45

I have a dataset with location-data. And in the GetLocation the data are transformed in a latitude and longitude value. That works fine. But when I returned to the html-page. The data is undefined. What is the reason? And how can I resolve this with JSon-data?

[HttpGet]
        public JsonResult GetLocation(Dictionary<string, string> items)
        {

                var result = "{ 'latitude': '" + latitude + "', 'longitude': '" + longitude + "'}";
                return Json(result);
            }

enter image description here

in the html:

    if (item.Location == null) {
        $.ajax({
            url: "@Url.Action("GetLocation", "Home")",
            dataType: "json",
            data: { items: item },
            type: "GET",
            success: (function (data) {
                location = JSON.parse(data);
            })
        });

        console.log("location:");
        console.log(location);
2 Answers

You are double-encoding the JSON here. The Json() function in the action method is encoding the string as JSON, which means the Javascript will be receiving something like this (note the quotes around the entire thing):

"{ 'latitude': '50.69093', 'longitude': '4.337744'}"

You should instead do something like this:

return Json(new { latitude, longitude }, JsonRequestBehavior.AllowGet);

Now in your success function, you will be able to access the values:

success: (function (data) {
    location = JSON.parse(data);
    console.log(location.latitude);
})

Note also the addition of JsonRequestBehavior.AllowGet, see here for why that is needed.

Please change like below

in MVC return type:

return Json(new { result = result }, JsonRequestBehavior.AllowGet);

in JQuery AJAX

location = JSON.parse(data.result);

Related