1

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.

2
  • you are mixing server side and client side code Commented Mar 4, 2021 at 20:02
  • It's the other way around -- you get the list from the controller from Javascript -- using AJAX. Commented Mar 4, 2021 at 20:02

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.