Exploring a JSON data structure in JavaScript using Asp.net

In my code behind file, I have serialized data as JSON. Here's a snippet of the code:


public class PieModel {
    public string label { get; set; }
    public double data { get; set; }
}

var data = new List<PieModel> {
    new PieModel { label = "Pending", data = 10d },
    new PieModel { label = "New", data = 40d },
    new PieModel { label = "Overdue", data = 50d }
};

hdnData.Value = new JavaScriptSerializer().Serialize(data);

When reading this serialized data in JavaScript, I do it like this:

var tempHdnData = $("#hdnData");

Now, I need to iterate over tempHdnData in order to extract and use the 'label' and 'data' members separately in my JavaScript code. How can I accomplish this task?

Answer №1

To implement this functionality in your code behind, you can structure your code as follows:

protected List<PieModel> GetChartData() {
    return new List<PieModel> {
        new PieModel { label = "In Progress", data = 20d }
        new PieModel { label = "Completed", data = 60d }
        new PieModel { label = "Not Started", data = 20d }
    };
}

Incorporate the chart data into your web form like so:

var chartData = <%= new JavaScriptSerializer().Serialize(GetChartData()) %>

You can then iterate over the data using jQuery:

$.each(chartData, function (_, item) {
    console.log(item)
})

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

The 'FileNotFoundException' error was triggered due to the 'Copy local = false' setting

I have around 20 solutions, each with 5-10 projects that reference each other and some third-party libraries. All of these projects are built in the same Output folder, and the requirement is to not have any duplicate copies of each assembly being referenc ...

The Text.Length function is not providing the correct length of a String for a web element

The value of "total" is 0 in this scenario. I'm unsure why it's not functioning properly? List<IWebElement> elementsList = new List<IWebElement>(); elementsList = ABCPageObject.AbcTextArea().ToList(); foreach (IWebElement element in ...

Trigger modal on designated ID

My code includes a script that assigns a specific id to a button using a variable $i in a for loop: <button id='myBtn$i'>Open Modal</button>. This id should allow me to open specific modals with the corresponding $i value: <div id= ...

Guide on using PHP to remove the trash icon glyphicon

I am currently creating a data table that includes various actions, one of which is the option to delete a row from both the table and the database. My challenge lies in figuring out how to successfully delete a particular row by simply clicking on the Tr ...

"Exploring the World of App Development with Visual Studio and Mobile

If I were to focus on developing for mobile phones (such as Android and Windows Phone 8) using HTML5, CSS, and Javascript clients, what type of project should I use in Visual Studio 2012? I assume ASP.Net, but I can't find any specific details about ...

Bar chart with overlays in Chart.js

I am currently working with a ChartJS bar chart and attempting to create overlapping bars. Each date should have three bars, each overlapping the others. Here is my idea: The bar with the highest value should have a z-index of 0, making it the tallest co ...

How to utilize regular expressions in JavaScript without the need to instantiate a regex object

Here is a code snippet that checks a URL for a specific pattern: var url = "https://www.google.co.uk/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=regex%20javascript"; var patt = new RegExp('https?:\/\/[^/]+\.google ...

Ways to resolve issues with queryStringParameters in an Exception

Trying to retrieve GET request parameters: An exception occurs when there are no parameters present. event = objectMapper.readTree(input); JsonNode queryParameterMap = event.findValue("queryStringParameters"); Interestingly, there is no excepti ...

Setting up an Express route for updating data

I am in the process of developing a MEVN stack CRUD application (Vue, Node, Express, MongoDB). I am currently working on setting up an Express route for handling updates in my app... postRoutes.post('/update/:id', async(req, res)=> { cons ...

Understanding the concept of Swift Optionals and handling partially populated JSON responses in REST handlers

When my REST API is capable of sending partial responses back, such as outlined in the documentation at this link, I'm left wondering if it's ideal to designate all properties in my Swift objects as optional. Is there a different approach I shoul ...

Ways to calculate the total quantity of items in the cart

Currently, I am in the process of developing an e-commerce website where users can add items to their shopping cart. Each time a user adds an item to the cart, it is stored in a table. The challenge I am facing now is figuring out how to dynamically count ...

single-spa: revolutionizing console.log for each microfrontEnd

Imagine having multiple single-spa react microfrontend apps in your project, such as Cart and Products The goal is to modify console.log, console.error, etc. so that they include a prefix indicating the corresponding microfrontend app: console.log call ...

Interpreting Multilayered JSON Objects using JQuery

Hello everyone! I've posted my sample json data below. While I am proficient in PHP, I am relatively new to jQuery. "data":{ "cipher":"true", "size":[ "2.2 Mb", "6.11 Mb", "9.25 Mb", ...

Displaying only the matched column in an Angular table

I am attempting to display only the matched columns in a table, but I am unsure of how to achieve this. If anyone has any ideas or solutions, please help me out. app.component.ts: columnsOnly = ['name', 'id', 'rank']; ite ...

Error: An attempt to make changes to a database that does not permit mutations has resulted in an InvalidStateError

I am facing an issue while attempting to initiate a transaction within the then() function. An exception is thrown when I try to do so. Below is the code snippet in question: open.onsuccess = function (e1) { var dbase = e1.target.result; $.get("https://w ...

A conditional stimulus for absence or lack of presence in the input request

The Jolt transformation process should be able to effectively handle scenarios where the request data is null, empty, or absent. Its role is to transform the input data into the desired output as defined in the Jolt specification. These transformations are ...

What is the best method for caching inline SVG in web browsers?

Over the years, SVGs have remained popular due to their scalability. One key advantage of inline SVG is the ability to manipulate it with CSS and JS. Additionally, using the <use> tag allows for referencing the original element when repeating the sam ...

specific term within a collection

I'm looking for a method to determine whether the word "miami" is present in this array and then display a message confirming its existence. I am contemplating whether to utilize a for loop or forEach loop. How can I verify if the word "miami" exists ...

Tips on refreshing a React component by using an input value sent from a separate component

Newbie Query in React/JS - Within my React application, there is a search bar enclosed in the 'Navbar' element and a 'FilmTable' component that exhibits the results of a fetch command in a table on the main page. Upon the initial rende ...

I encountered a [json.exception.type_error.302] while troubleshooting my code. Although I understand the error message, pinpointing the exact source of the issue remains a challenge

I have a program that analyzes the values of samples in a JSON file, calculating sorting comparisons, memory usage, and sorting time. However, I encountered an error in the code and would appreciate some assistance. I'm receiving a [json.exception.typ ...