Transmit a JSON array from a controller to a JavaScript variable

I have retrieved a JSON array from a database and it is set up in a controller like this:

public ActionResult highlight()
{
    var statesHighlight =
        db.Jobs
            .Select(r => r.State);
    return Json(statesHighlight , JsonRequestBehavior.AllowGet);
}

How can I assign this as a JavaScript variable in my view? I believe there must be an easy way to do it, but I am unable to figure it out. Should I use @Html.Action or @Url.Action?

EDIT: This is how I currently have my data hardcoded for the plugin that I am using:

<script type="application/json" id="map-data">
    ["CA","UT","FL","MT","WA","KS","KS","UT"]
</script>

<script>
    var data = $.parseJSON($('#map-data').text());
    var cities = $.parseJSON($('#city-data').text());


    $('img').mapster({
        mapKey: 'state',
        clickNavigate: true,
        isSelectable: false,
        highlight: false,
        onConfigured: function () {

            // make the array into a comma-separated list
            var csv = data.join(',');

            var city_list = cities.join(',');

            // the 'set' activates the areas
            $('img').mapster('set', true, csv, options = { fillColor: '638EA5' });
            //altImage: '../Images/map_outline_blackStrokeDot.png'
            $('img').mapster('set', true, city_list, options = { fillColor: 'ffffff' });
        }
    });
</script>

Answer №1

Take a look at this:

<script type="text/javascript>
    $(function () {
        $.getJSON('getarray'
            , null
            , function (data) {
                console.log(data);
            });
    });
</script>

Here is the controller code:

    public JsonResult GetArray()
    {
        string[] myArray = {"apple", "orange", "banana"};

        return Json(myArray, JsonRequestBehavior.AllowGet);
    }

In your controller, you may need to use ToArray when executing the query.

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

Generate clickable links on a web page with PHP and a form

Every week I find myself tediously creating links by manually copying and pasting. It's starting to feel like a crazy process, and I'm sure there must be a faster way. A123456 B34567 d928333 s121233 I need these numbers to be transformed into h ...

Axios is causing my Pokemon state elements to render in a jumbled order

Forgive me if this sounds like a silly question - I am currently working on a small Pokedex application using React and TypeScript. I'm facing an issue where after the initial page load, some items appear out of order after a few refreshes. This make ...

Can data be retrieved from a redirection page using AJAX?

I'm facing a challenge. I am attempting to complete a task that seems simple, but I am struggling with it. Let me explain the situation: I have 3 different HTML pages: The first page, named index.html, is my main page with a button that triggers a ...

Unable to interpret JSON input when calling Bing Distance Matrix API from PHP

While I have successfully made a call to the Bing distance matrix service using Postman, I am encountering issues when trying various cURL methods and Unirest in my application where I pull data from MySQL. The error message I receive is: JSON input cou ...

Insert a fresh key-value pair into a JSON document using Powershell

Recently, I've been working with a JSON file that looks like this: { "buildDate": "2017-08-16", "version": "v1.2.0" } I've been wondering about how to add new key-value pairs to an existing JSON file. For instance, starting with the J ...

Is there a way for me to retrieve a variable from outside a function?

I'm trying to access a variable outside of the function in Next.js. I want to retrieve the 'name' from the data object after making an API call. let getDetail = async () => { let body = { code: '12', provider: & ...

Achieve the appearance of a galloping horse using JQuery

I am looking for a way to create the illusion of a horse running by displaying a sequence of images quickly. Each image in my folder shows the horse in motion, and I want to make it appear as if the horse is actually moving. Can anyone recommend a librar ...

Questions about clarifying JS promises and async-await functions

After doing some reading on promises in JavaScript, I have come across conflicting information which has left me with a few basic questions. I have two specific questions that need clarification: Is it necessary for every function in JavaScript to be ca ...

The variable fails to receive the AJAX response

Trying to retrieve the content of data.dat, I have utilized the following code. Below are the relevant files: main.js function getData() { var result; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState ...

Which is better for creating a gradual moving background: Javascript or CSS?

I'm attempting to discover how to create a background image that scrolls at a slower pace than the page contents. I'm currently unsure of how to achieve this effect. A great example of what I'm aiming for can be seen here Would this require ...

Creating an object key using a passed literal argument in TypeScript

Can the following scenario be achieved? Given an argument, how can we identify the object key and access it? Any potential solutions? async function checkKey(arg:'key1'|'key2'){ // fetchResult returns an object with either {key1:&apo ...

Having trouble terminating the session with the authentication provider SSO on Node JS

I'm struggling with ending the session properly when a user makes a request to my /logout endpoint. I want to clear the session and require the user to log in again via SSO. Currently, after an initial login, I remain logged in without needing to re-e ...

What could be causing this empty Ajax ResponseText?

$("b_xml").onclick=function(){ new Ajax.Request("books.php", { method:"GET", parameters: {category:getCheckedRadio(document.getElementsByName("category"))}, onSuccess: showBooks_JSON, onFailure: ajaxF ...

How to incorporate "selectAllow" when dealing with dates in FullCalendar

I've been attempting to restrict user selection between two specific dates, but so far I haven't been able to make it work. The only way I have managed to do it is by following the routine specified in the businessHours documentation. Is there a ...

Oops! Looks like there's an issue with reading the property 'value' of undefined in React-typeahead

Having some issues with setting the state for user selection in a dropdown menu using the react-bootstrap-typeahead component. Any guidance or resources on this topic would be highly appreciated. Details can be found here. The function handleAddTask is su ...

Is it considered best practice to call the same function within itself in a function?

function takeANumber() { let startHealth = parseInt(prompt("Please enter a positive number:")); // I am recursively calling the same function within an if block to ensure that the input is a valid number greater than zero. Is this considered good practic ...

Retrieving a function from a JavaScript file located in a publicly accessible directory

Having trouble accessing a function from the JS file scripts.js within the public folder where my CSS file is also located. Despite following various tutorials like this, I keep encountering the error message Error: Cannot find module './scripts.js&ap ...

Restricting the number of times a user can click on

I am currently displaying a table with data obtained from a database query. The structure of the table is outlined below: <table id="dt-inventory-list" class="table table-responsive"> <thead> <tr> <th>Field ...

Retrieve the full user profile information from the Magento Database

Is it possible to incorporate Magento Login credentials into another website as well as an Android application? Essentially, users would have a single account on a Magento-based site and be able to log in from their Android device. I've attempted to r ...

Error: The value extracted from the JSONObject is not being passed to the response

As a beginner in Android development, I am struggling to save the userid and retrieve it from the try-catch statement. Despite facing issues with AlertDialog functionality, I appreciate any assistance provided. EDIT: Upon further investigation, I disc ...