Sending information from the Controller to a JavaScript function

Within my controller, the following code is present:

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();
    }

I aim to pass this list to the View so that when loaded, I can incorporate markers onto a 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);
    }
}

However, queries have arisen as it seems data cannot be passed in such a manner. I am now at a standstill and unsure of how to transmit data from the controller to JavaScript for marker creation purposes.

Answer №1

Revise your strategy:

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

Update your perspective:

@model List<UserNeighborhoodData>
....

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

..... your code

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to saving a JSON array to a file using a writeStream in Node.js

I created a Node.js script to scrape data from a website, with the process involving iterating through pages to collect structured data. Every page yields an array of objects as the data I extract. My initial plan was to utilize the fs.createWriteStream( ...

The Vimeo player JavaScript API is experiencing issues on iOS devices

I am facing an issue where the API for playing a video only works on iOS after the play button is clicked in the player. However, it works fine on desktop and Chrome for Android. http://codepen.io/bdougherty/pen/JgDfm $(function() { var iframe = $(&a ...

Substitute <br /> tags with a line separator within a textarea using JavaScript

Anyone have a quick fix for this? I've been searching online for a solution, but no luck so far. Already tried checking out: this, this Currently dealing with a textarea that receives data from AJAX call and it ends up looking like this: Hello& ...

What is the best way to include the ID in a Vue.js Ajax request for posts?

Is there a way to pass an "id" obtained as data in vue js? The id is coming as "agnt.basic.actor". Considering the presence of multiple ids, how can I achieve this? <tr v-for="agnt in agentlist"> <td v-if="agnt.basic">{{agnt.basic.actor}}< ...

There was an error in Threejs' PropertyBinding as it attempted to parse the trackName ".bones[].position

Version: THREE.WebGLRenderer 91dev Struggling to achieve a basic chest opening animation using three.js. Unfortunately, encountering an error while trying to create an action. PropertyBinding: Unable to interpret trackName: .bones[].position Link to t ...

How to write a more advanced Path for Selenium Chrome WebDriver using C#

I am struggling to find the correct path to click on a specific button on my webpage. To help illustrate, I have provided a sample page for testing purposes. All you need to do is download the HTML file and open it in your browser.Code of HTML page What ar ...

Tips on efficiently adding and removing elements in an array at specific positions, all the while adjusting the positions accordingly

My challenge involves an array of objects each containing a position property, as well as other properties. It looks something like this: [{position: 1, ...otherProperties}, ...otherObjects] On the frontend, these objects are displayed and sorted based on ...

Schema for Monogo Database

My goal was to have a property that could give me the timestamp of when a specific task was created. I decided to add a timestamp property and set it to true, but now my code won't compile. The code is functioning perfectly fine without the timestamp ...

Creating your own JsonConverter in JSON.NET: A step-by-step guide

I have been exploring how to expand upon the JSON.net example provided in In my scenario, I have a subclass that inherits from a base class or interface. public class Person { public string FirstName { get; set; } public string LastName { get; se ...

Retrieve the CSS class definition using the console in the Chrome Developer Tools

Is there a way to automatedly extract CSS class definitions from Chrome Developer Tools? I want to retrieve the styles defined in a specific class name, similar to how it is displayed in the Styles tab on the right-hand side. I know about the getComputedS ...

The SVG element seems to have a mind of its own, refusing to obey my CSS commands and stubbornly remaining centered on the screen. I'm at a loss as

I am facing an issue with positioning SVG elements on a web page. Even though I have set the x,y coordinates to 0,0 and used CSS to position it on the left side of the page, the SVG remains in the center. Here is a link to the problem replicated in jsFidd ...

Utilizing DllImport in a class library or web service project

I've developed a console application that imports a "C" Dll using DllImport. The "C" Dll has references to other Dlls and Config files in the same folder. When I place all the files in the bin directory of the Console application, everything works pe ...

Make an AJAX GET call to an ASP.NET Web API endpoint

Here is the ajax script I am using: $.ajax({ dataType: 'json', url: url, data: tuDispId, type: "GET", success: function (data) { bindData(data); $("#ale ...

Are you in need of a JavaScript data validation tool?

Trying to find a library that can validate input in a specific format, such as: { points: array of { x: positive and less than 20, y: positive and less than 15 } } Ideally, it should work on both server and client sides and either return a boolean or th ...

Issue with swal() not triggering in Internet Explorer 11

Looking for some assistance here, I believe I might be missing a small detail. The _layout.cshtml file includes all the necessary scripts to ensure that sweetheart works on IE: (this used to work in previous versions, but we haven't had to support I ...

HTML is not connecting to CSS

I'm having trouble linking my external CSS to my HTML file. In the head of my index.html, I have this code: <head> <title>Twenty by HTML5 UP</title> <meta charset="utf-8" /> <meta name="viewport ...

How to transition from using a CDN to NPM for implementing the Google Maps JavaScript MarkerClusterer?

Currently integrating Google Maps JavaScript MarkerClusterer from CDN, I am considering transitioning to the NPM version for Typescript checking in my JavaScript files. However, I am encountering difficulties understanding how to make this switch. The docu ...

Creating a unique 3D model through specified coordinates with the use of THREE.js

I possess an array consisting of (x,y,z) vertices coordinates as well as a facets array that stores the indexes of vertices (taken from the first array) for each facet. Each facet may have a varying number of vertices. Is there a way to construct a unique ...

Using string keys in ASP.Net OData Framework

I am struggling to implement ASP.Net OData v4 (specifically ODataController) to allow access with a string key. Most of the examples available online use an integer key, and the few resources discussing how to use a string key are not providing the desired ...

Javascript time conflict dilemma

Currently, I am working on the add task module for my project. I need to ensure that whenever a task is added, it does not overlap with existing tasks. I have almost completed this functionality, but I have encountered a problem specifically with time over ...