Данные не поступают из действия JsonResult в сценарий Javascript - PullRequest
0 голосов
/ 26 апреля 2019

Как видно из названия, я не могу получить и использовать данные из базы данных в моем javascript.У меня есть контроллер, в котором у меня есть конструктор контекста базы данных и действие JsonResult, в котором информация поступает так, как должна, но когда я пытаюсь использовать данные в javascript, она кажется мне пустой.Вот мой контроллер:

namespace ProiectColectiv.Controllers
{
    public class AdminMapController : Controller
    {
        private readonly ProiectColectivContext _context;

        public AdminMapController(ProiectColectivContext context)
        {
            _context = context;
        }

        public ActionResult AdminMap(User user)
        {
            return View("~/Views/Home/AdminMap.cshtml", user);
        }

        public JsonResult GetAllLocation()
        {
            var data = _context.Parkings.ToList();
            return Json(data);
        }
    }
}

Вот мой .cshtml с javascript:

@*@model ProiectColectiv.Models.Parking*@
@{
    ViewData["Title"] = "Admin Map";
}
<br/>
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
        #map {
            height: 800px;
            width: 1200px;
        }

    </style>    
</head>
<body>
<div id="map"></div>
<script>
    var map;
    function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
            center: { lat: 46.770920, lng: 23.589920},
            zoom: 13
        });

        $.get("@Url.Action("GetAllLocation","AdminMap")", function (data, status) {
            var marker = [];
            var contentString = [];
            var infowindow = [];
            for (var i = 0; i < data.length; i++) {

                marker[i] = new google.maps.Marker({ position: { lat: parseFloat(data[i].Latitudine), lng: parseFloat(data[i].Longitudine) }, map: map });

                contentString[i] = '<div id="content">' +
                    '<div id="siteNotice">' +
                    '</div>' +
                    '<h1 id="firstHeading" class="firstHeading">'+ data[i].Name+'</h1>' +
                    '<div id="bodyContent">' +
                    '<p><b>' + data[i].Name +'</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
                    'sandstone rock formation in the southern part of the ' +
                    'Northern Territory, central Australia. It lies 335&#160;km (208&#160;mi) ' +
                    'south west of the nearest large town, Alice Springs; 450&#160;km ' +
                    '(280&#160;mi) by road. Kata Tjuta and Uluru are the two major ' +
                    'features of the Uluru - Kata Tjuta National Park. Uluru is ';
                infowindow[i] = new google.maps.InfoWindow({
                    content: contentString[i]
                });

                //marker[i].addListener('click', function() {
                //    infowindow[i].open(map, marker[i]);
                //});
            }
        })

    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD9HfqjqR0VDGD5N1sCd_nU8qC7J5SXATM&callback=initMap"
        async defer></script>
</body>
</html>

А вот моя модель:

namespace ProiectColectiv.Models
{
    public class Parking
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public double Longitudine { get; set; }

        public double Latitudine { get; set; }
        public int NrFastChargingSpots { get; set; }

        public int NrNormalChargingSpots { get; set; }

        public List<Station> Stations { get; set; }
    }
}

Любая идея, почемуданные не передаются в javascript?Любая помощь будет принята с благодарностью.

Ответы [ 2 ]

1 голос
/ 26 апреля 2019

Я думаю, вам нужно добавить JsonRequestBehavior.AllowGet в качестве второго параметра в методе Json().

return Json(data, JsonRequestBehavior.AllowGet)
0 голосов
/ 26 апреля 2019

Решено. Проблема была в том, что return Json(data) возвращал строку, что-то вроде {name: "x"}, и я пытался принять ее как data.Name, и я должен был сделать это как data.name, как это происходит от json.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...