Tips for creating a JSON object list

I'm currently working with asp.net mvc2 and attempting to send a list of JSON objects with predefined values from the home controller, then receive them in the index page.... the code snippet below shows how I am sending a single JSON object .... but how can I send multiple objects at once?

Here is the code in the home controller:

public ActionResult JsonValue()
        { 
            var result = new 
            { 
                pID = 1, 
                pName = "Lina",
                pStart = "",
                pEnd = "",
                pColor = "ff0000",
                pLink = "",
                pMile = 0,
                pRes = "Brian",
                pComp = 0,
                pGroup = 1,
                pParent = 0,
                pOpen = 1
            };


            return Json(result,JsonRequestBehavior.AllowGet);

And here is how you would receive it in the index page:

        var Jid = null;
        var Jname = null;
        var Jstart = null;
        var Jend = null;
        var Jcolor = null;
        var Jlink = null;
        var Jmile = null;
        var Jres = null;
        var Jcomp = null;
        var Jgroup = null;
        var Jparent = null;
        var Jopen = null;
        var Jtitle = null;
        var g = new JSGantt.GanttChart('g', document.getElementById('GanttChartDIV'), 'day');
        $(document).ready(function () {

            $.getJSON('../../Home/JsonValue', function (data) {
                Jid = data.pID;
                Jname = data.pName;
                Jstart = data.pStart;
                Jend = data.pEnd;
                Jcolor = data.pColor;
                Jlink = data.pLink;
                Jmile = data.pMile;
                Jres = data.pRes;
                Jcomp = data.pComp;
                Jgroup = data.pGroup;
                Jparent = data.pParent;
                Jopen = data.pOpen;
                Jtitle = '|id= ' + Jid + '|Name: ' + Jname + '|Start: ' + Jstart + '|End: ' + Jend;

            }); // end $.getJSON

Thank you very much for any help you can provide! -Lina

Answer №1

Store the values in an array and then return it using JSON.

In my opinion, it would be better to create a class instead of using an anonymous object. You can add objects of this class to a generic list, and then convert the list into an array before passing it to the JSON call. Alternatively, you may directly pass the generic list to the JSON call as it seems that JSON can handle any enumerable type.

Upon further investigation,

It appears that JSON automatically converts any enumerable into a JSON array. Therefore, it should be possible to pass the generic list directly. I will provide some sample code later

Code snippet added below:

I don't recommend coding a List<object>. Instead, I suggest creating a dedicated class for your objects so that they are strongly typed. Here is a basic example:

public ActionResult JsonValue()
{
    List<object> jsonlist = new List<object>();
    jsonlist.Add(new
    {
        pID = 1,
        pName = "Lina",
        pStart = "",
        pEnd = "",
        pColor = "ff0000",
        pLink = "",
        pMile = 0,
        pRes = "Brian",
        pComp = 0,
        pGroup = 1,
        pParent = 0,
        pOpen = 1
    });

    // Add more objects to the list here

    return Json(jsonlist,JsonRequestBehavior.AllowGet);
}

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

How can I pass the current value of an HTML.DropDownListFor to an ActionLink?

Is it feasible to transfer the current value of @Html.DropDownListFor to an action link? I am trying to send the template value to the Sample controller using the Create action. The code below is not functioning because @Model.SurveyTemplate does not retur ...

Before the custom font finishes loading, useEffect is triggered

Custom font usage in my app: @font-face { font-family: "Koulen"; src: url("./assets/fonts/Koulen-Regular.ttf") format("truetype"); } body { font-family: "Koulen"; } An issue arises as the useEffect is called ...

The has-error class cannot be applied to certain input elements

I am currently in the process of validating some inputs within a modal: <div id="modal-section" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="m ...

What causes the issue of text being blocked by a webgl shader background even when the text div is layered above and given a higher z-index?

I am looking to enhance a WordPress theme by dynamically generating glsl shaders using the three.js library for JavaScript, and then incorporating those shaders into various HTML elements, such as using them as backgrounds for text content. My current cha ...

The POST method in Node JS request-promises does not properly handle string inputs

When I am trying to establish a connection between my node.js module and another server, I utilize the 'request-promise' library. My implementation for posting data looks like this: rp.({ method: 'POST', headers:{ 'Conte ...

"Enhanced interactivity: Hover effects and selection states on an image map

Hello there, I need assistance with my code. Here it is: <img id="body_image" usemap="#body_map" src="assets/images/body.jpg" alt=""> <map name="body_map"> <area shape="poly" alt="d" href="#body_chart" name="ad" coords="153, 153, 145, 1 ...

Retrieving field-value pairs from a JSON object within a MariaDB database

Hi there! I am struggling to extract the field values of a JSON object as key value pairs. Here is what I have tried: SELECT JSON_EXTRACT(chapters, '$[*].Id', '$[*].Name') AS rec FROM `Novels` WHERE 1 However, the result looks lik ...

What steps can be taken to resolve the mouse-pointer problem?

Currently, I am utilizing PHP, jQuery, JavaScript, and other tools for my website development. I have a new requirement for a script in jQuery/JavaScript that can trigger an alert when the user's mouse-pointer moves away from the tab where my website ...

Executing JavaScript functions within static files in Django

I can't figure out why I'm unable to invoke a javascript function when clicking my Bootstrap button in a Django project. In my directory, I have set up the static folder as "main/static/main/js/script.js". While I can successfully load the stati ...

PHP cURL is essential for me to access information

Set ( [result] => 1 [data] => Set ( [0] => Set ( [unique_id] => 123456789 [name] => rig2 [description] => rig2 ) ...

Encountering the issue: "To proceed, queries must include at least one table or query."

Currently, I am working on building a form using visual studio 2010 that allows users to edit, delete, or insert data from an accessdatabase. However, when attempting to run the form in a web browser, I encountered the error message "Query input must con ...

Is there a specific measurement or scale for the dragging feature in jQuery UI draggables?

I'm interested in adjusting the position of my draggable element based on the distance moved by the mouse. For instance, if the scale is 1:2 and the cursor is moved 10px to the right, then the draggable should move 20px. I already have my draggable ...

Tips for optimizing AngularJS performance with large scopes

Currently, I am working on an Angular app for my company and have encountered a major issue. The app has become extremely slow, even after trying to optimize it using techniques like onetimebind and track by. Despite initial improvements, the performance i ...

Issue with jQuery centering in IE browsers with jquery-ui-1.10.3.custom.js and jquery-ui-1.9.2.custom.js not working as expected

Are there any other alternatives you can recommend? Here is the dialog structure: <div id="dialogbox" title="message box"> <p>example content</P> </div> ...

Extracting individual items from JSON using a regular expression condition

Utilizing the Google Vision API in my project has been a game-changer. The OCR result provides a JSON file that captures all recognized items along with their coordinates. Now, I am seeking to implement a feature that will sift through this JSON data, iden ...

iOS Chrome: Enabling Cookies with "Always Allow"

While the Safari browser on OSX has a setting under Privacy & Security -> Block Cookies -> Always Allow, enabling the storage of entries in the browser's local storage even when accessing pages from third party sites like those running in an ifr ...

Obtaining a JSONObject for a RealmObject requires a specific process

Currently, I am using Retrofit2 to fetch data and storing it in Realm. However, I am struggling to extract a JSONObject from another JSONObject and save it into a RealmObject. Can anyone guide me on how to define my RealmObject model for this scenario? I a ...

Tips on accessing data from Parsed JSON Object with Array.prototype.find() or Array.prototype.filter()

I have a JSON Object that has been parsed as shown below. [ { id: 973276, raw: 'Apple Tree Childcare', extractedData: null }, { id: 973576, raw: 'Yes', extractedData: 'Yes' }, { id: 973567, raw: 'Road', extractedD ...

A guide on extracting a URL from source tags using Cheerio/jQuery

I have been struggling to retrieve the first image with data-srcset attribute ("https://sample.img_1") using Cheerio. None of my previous attempts have been successful. My most recent attempt looks like this: $(".sample_picture [media='(max-width: 64 ...

How do I reduce the size of a WinJS image file

Can anyone help me figure out how to retrieve the size (in pixels, bytes) of a picture in a Windows 8 app? I'm using openPicker to select the file but can't seem to find the size attributes. I want to display an error message if the file is too ...