2

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);
user1531040
  • 2,143
  • 6
  • 28
  • 48
  • What do you mean by "undefined"? What is in the `data` variable? Also, you're double-encoding the JSON here. The `Json` function in the action method is encoding the string as JSON. You could instead do `return Json(new { latitude, longitude });` – DavidG Jul 15 '21 at 10:11
  • data is the input for the GetLocation-action. It's read as a Dictionary with keys and values. The output has to be an object with two values Latitude and Longitude. – user1531040 Jul 15 '21 at 10:50
  • I meant the data parameter in the `success` method. – DavidG Jul 15 '21 at 11:25

2 Answers2

2

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.

DavidG
  • 113,891
  • 12
  • 217
  • 223
  • Thank you. This is a part of the solution. I have added contentType: "application/json", async: false, and cache: false in the Ajax-call. That works for me. – user1531040 Jul 19 '21 at 11:03
-1

Please change like below

in MVC return type:

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

in JQuery AJAX

location = JSON.parse(data.result);

  • That is still going to double-encode the string as JSON, but now it's nested inside another object. This is only going to make things worse. So now it would return this `{"result":"{ 'latitude': '50.123', 'longitude': '4.123'}"}` – DavidG Jul 15 '21 at 10:21