Query regarding JSON format

If I have a database table named User with fields for name, Id, and age, how can I retrieve this data as JSON and send it to a JavaScript page? I want to customize the way the data is displayed on the frontend. Specifically, I need help understanding how to store the data in a variable as JSON and manipulate it in the JavaScript file (such as accessing array[name]).
Would it be better to handle this data manipulation in ASP.NET code before sending it to JavaScript, or should I send the raw data to JavaScript and then work with it there? Thank you! :D

Answer №1

Serialization of objects in .NET can be achieved using the JavaScriptSerializer

List<User> allUsers = RetrieveAllUsers();
string usersJson = new JavaScriptSerializer().Serialize(allUsers);

By doing this, you eliminate the need to worry about escaping quotes or other characters. Once you have this JSON string, you can utilize it in your JavaScript code:

var usersJson = ... // the JSON string
var parsedUsers = JSON.parse(usersJson);

Conversely, if you have a JavaScript object that needs to be sent to the server:

var usersData = ... // a JS object
var usersJson = JSON.stringify(usersData);

You can then deserialize the string usersJson when it reaches the server. If the structure of the JS object matches exactly with a .NET object or an array of .NET objects, you can deserialize it as follows:

List<User> deserializedUsers = new JavaScriptSerializer().Deserialize<List<User>>(usersJson);

If there is no direct mapping between the JS object and a .NET object, you will need to use:

object deserializedData = new JavaScriptSerializer().DeserializeObject(usersJson);

Answer №2

Discover insightful articles from 4guysfromrolla that will guide you through the intricacies of the topic.

https://web.archive.org/web/20220111093442/http://www.4guysfromrolla.com/articles/102010-1.aspx

https://web.archive.org/web/20220315081217/https://www.4guysfromrolla.com/articles/040809-1.aspx

Explore these resources for a comprehensive grasp of the subject matter.

If you simply need to showcase query results on the UI, consider utilizing gridview or repeater controls for seamless presentation.

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

Tips for setting React state using variables as keys or values

Although I managed to achieve the desired result, I'm still puzzled as to why my more straightforward approaches didn't work. Can someone help me understand what's going on here? Basically, I needed to set nested state at different levels u ...

I'm having trouble getting my HTML page to display appended text. What could be causing the issue?

let mainDiv = document.getElementById("main"); let myParagraph = document.createElement("p"); let myTextNode = document.createTextNode("hello"); myParagraph.append(myTextNode); mainDiv.append(myParagraph); let max = 25; let on ...

Is it impossible to access the length property of an undefined variable?

After developing a function that calculates the length of a string entered into an HTML textbox, I encountered an error when trying to display the result in another textbox. The function is designed to get the value from the 5th textbox on my HTML page and ...

Does the 'a' HTML tag secretly trigger window.location.assign?

Being relatively new to the online world, I have a simple question in mind. Imagine that I have a very basic a tag in my HTML: <a href="www.google.com"> Click me </a> What actually happens when I click on this link? Does the browser simply ...

Ensure confirmation dialog box pops up multiple times when deleting an item using AJAX

On my website, I have a side menu with multiple navigation items. In the admin section, there is a table where I can manage these items. The issue arises when I delete an item from the table using ajax - it gets deleted from both the table and the side men ...

How can data be transferred between web pages using jQuery or JavaScript?

Imagine having two different pages on a Classified car website: The first page is the search page, which displays a list of all cars. Check out a sample search page here The second page is the details page, where you can find specific information about a ...

Storing a string in a variable within Typescript

Attempting to read an XML file in Typescript using some JavaScript code, with the goal of adding the text content to a local variable. The code snippet is as follows: import { Injectable } from '@angular/core'; @Injectable() export class Jsonre ...

The MSW handler successfully intercepts the request, yet an Axios network error still persists

I'm feeling a bit stuck - I've gone through numerous posts here discussing the combination of Axios and MSW [1] [2] [3], but I still can't quite pinpoint where my mistake lies. My goal is to utilize MSW to intercept network requests made by ...

Deciding the result of a jQuery dialogue and storing the result in a variable

Instead of using a standard confirm dialog box in JavaScript, you can customize and style it using the jQuery UI dialog. Here's an example: // Initialize variable as false var shouldIngest = false; // Open jQuery UI dialog with custom styling $(&apo ...

Discovering the right data through date without using a function

I have a mongodb collection with a date property and I need to search for objects with a date greater than a specific date string. I am using the node.js native driver, but running into issues with the query. Here is what I have tried so far: db.myCollect ...

The datatable fails to render after executing a function in AngularJS

When I load the page without calling a function, the data is displayed in a datatable perfectly fine. However, if I try to generate the datatable after calling a function, it does not work. HTML: <div class="widget-body no-padding"> ...

Step-by-step guide on programmatically closing the Material-UI DropDownMenu

http://www.material-ui.com/#/components/dropdown-menu Having encountered a styling issue, I was compelled to rearrange the order of components within my material-ui DropdownMenu. Nevertheless, some buttons (renderNavLink) are now failing to close the Dro ...

What is the best way to obtain various classed elements within a single node list?

I'm trying to select two different elements with different classes within the same node list. For example, if I could use this code: document.querySelectorAll(".a, .b"); It would mean selecting elements with the ".a" class, but also including any el ...

Data-binding between X and Y axes in several grouped bar charts using d3.js

Check out this Fiddle Example I've been exploring different approaches for creating multiple grouped bar charts on a single page. I came across two examples (Example 1) and (Example 2), but I'm facing an issue with setting the X and Y domains co ...

A guide on unescaping HTML characters while encoding JSON in Python

Is there a way to unescape HTML characters in string fields before sending out JSON data? I thought about creating a custom json.JSONEncoder to handle this. Below is an example of what my encoder looks like: import jinja2, json class EscapingJSONEncoder( ...

Is it possible to transform div containers into unique shapes?

I'm working on a design where I want to have two divs that resemble teeth, one on the top half of the page and the other on the bottom half. The concept is to make these mouth piece divs open and close as you scroll with the mouse, revealing the conte ...

In order to have JavaScript showcase a random word from a list when a button is clicked and then display it in a heading 3, follow these steps:

How can I create a JavaScript function that displays a random word from a list when a button is clicked and prints it in a heading 3? I would appreciate a quick response. //Start of Js code let display = document.getElementById("motivato"); console.log(di ...

Issues with @material-ui/core and react-bootstrap imports are causing disruptions to the NextJS build process

After researching, I've come to realize that this issue is common among developers. Unfortunately, none of the solutions I found have worked for me. During npm run dev mode, everything in the project functions as expected, with all imports working se ...

What is the best way to iterate through a JSON object using the stages array provided?

I am facing an issue with parsing the provided json to display the desired output on the screen. These are the steps I need to follow for parsing this json: 1. Extract the stages array from the json - for example, stages ["check_dependency_progress", "sh ...

Is it possible for ASP.NET Core deserialization to assign null to a property if all of its child properties are null?

Within my ASP.NET Core 8 project, I am utilizing the CreatePerson Minimal API to handle incoming JSON data: { "name": "Peter", "residence": { "country": null, "status": null }, } For this JSO ...