简体   繁体   中英

Pass data from Controller to JavaScript function

I have this code in controller

public async Task<IActionResult> Index()
    {
        HttpResponseMessage responseMessage = await _httpClient.GetAsync(_getDataControlerApiUrl + "/getUserData");
        string stringData = await responseMessage.Content.ReadAsStringAsync();

        var options = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        };

        List<UserNeighborhoodData> data = System.Text.Json.JsonSerializer.Deserialize<List<UserNeighborhoodData>>(stringData, options);

        string aor = data.Where( x => x.Username == User.Identity.Name).FirstOrDefault().AOR;

        ViewBag.UsersData = JsonSerializer.Serialize(data.Where(x => x.AOR == aor).ToList());
        return View();
    }

and I want to pass that list to View so that on load I can add markers to map

@{
var userData = (List<UserNeighborhoodData>)ViewBag.UsersData;
 }

<div id="map" style="margin:10px; width:70%; height:770px;"></div>

<script>
mapboxgl.accessToken ='MY-KEY';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/outdoors-v11',
    center: [19.6860534, 45.1163156],
    zoom: 7.2
});
map.addControl(new mapboxgl.NavigationControl());

window.onload = function () {
    data = @userData
    var i;
    for (i = 0; i < data.Count; i++)
    {
        var popup = new mapboxgl.Popup({ offset: 25 }).setText(
            "Username:" + data[i].Username + "Energy to grid in this month: " +  data[i].CurrentSoldEnergyInAMonth
        );

        var el = document.createElement('div');
        el.id = 'marker' + i;

        new mapboxgl.Marker(el)
            .setLngLat([data[i].Longitude, data[i].Latitude])
            .setPopup(popup) // sets a popup on this marker
            .addTo(map);
    }
}

But it does not work, because I learned that is impossible to pass data that way. So I am now stack and don`t know how to pass data from controller to JavaScript code so I can create markers.

Change your action:

public async Task<IActionResult> Index()
    {
           ......
        var model = JsonSerializer.Serialize(data.Where(x => x.AOR == aor).ToList());
        return View(model);
    }

and your view:

@model List<UserNeighborhoodData>
....

window.onload = function () {
    
 var data= @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)) };

..... your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM