Decoding JSON information in ASP.NET using C# and the Razor engine

Hi there, I'm currently working in Visual Studio with ASP.NET and Razor. I am trying to populate a table with values from a database table, but I need to decode or parse JSON into simple text first. Any assistance would be greatly appreciated. Here is the code snippet that I am currently using: https://i.sstatic.net/K7imY.png

  [HttpGet]
        public ActionResult GetData()
        {
            string stdb = "Data Source=DMX87025;Initial Catalog=DB_PCC;Integrated Security=True";
            SqlConnection conn = new SqlConnection(stdb);
            string sql = "SELECT *FROM[DB_PCC].[dbo].[Departments]";
            SqlCommand cmd = new SqlCommand(sql, conn);
            conn.Open();

            SqlDataReader rd = cmd.ExecuteReader();

            var st = "kyo please help me u.u";
            return Json(new { success = true, message = rd },
                JsonRequestBehavior.AllowGet);
        }
This is the AJAX function that I have implemented...

<div id="result"></div>
<input type="button" name="name" value="try" onclick="DepListQuery()" />

<script>

    function DepListQuery() {

        $.ajax({
            type: 'GET',
            url: '@Url.Action("GetData","Home")',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {

                $('#result').text(response.message);
            },
            failure: function (response) {
                alert("something went wrong u.u");
            }
        });
    }   

</script>

Answer №1

To improve your data reading process from the SqlDataReader, it is recommended to utilize extension methods to read data directly into objects. A helpful tutorial on this topic can be found here:

For a more efficient approach, consider implementing extension methods as demonstrated in the following answer: Convert rows from a data reader into typed results

Here is an example of a sample extension method:

public static List<T> ReadList<T>(this IDataReader reader, 
                                  Func<IDataRecord, T> generator) {
     var list = new List<T>();
     while (reader.Read())
         list.Add(generator(reader));
     return list;
}

After calling

SqlDataReader rd = cmd.ExecuteReader();
, you can use the following code snippet:

var departmentList = reader.ReadList(x => new Department {
                                           DeptID = x.GetInt32(0),
                                           DeptName = x.GetString(1)
                                    });

Once you have populated a list of objects using this method, you can then handle them in the front-end view using AJAX:

How to parse JSON list of string on ajax return?

List of Objects To Json String

It is also advisable to enclose your database connections such as SqlConnection, SqlCommand, and SqlDataReader within using blocks for proper resource management.

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

Could not locate the provider: $stateProvider

It's puzzling to me why this code is not recognizing the $stateProvider. Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to: Error: [$injector:unpr] Unknown provider: $stateProvider This is a simple example of a module: ( ...

Implement input validation in React by enhancing the functionality of HTML input tags

Below is the input provided: const REGEX_EMAIL_VALIDATION = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}&bsol ...

Preserving Scroll Location Through Back Button Usage and Ajax Manipulation of the Document Object Model

Currently, I am incorporating a feature where results are loaded in using ajax with an infinite scroll. However, there is an issue when a user clicks on an item in the list and navigates away from the page - upon returning by clicking the back button, they ...

Ways to automatically update options in a dropdown menu using text box entries

When a character is typed into the text box, I want the select box to display options that contain that character. For example, if I type 'a', the select box should show "Anand", "Arun", and "Ananya". If I then type 'n', only "Anand" an ...

What is the process to change the jQuery quiz outcome into a PDF when a user clicks a

I'm currently working on a jQuery quiz project where I want users to be able to download their results in PDF format with just one click. After doing some research, I came across the dompdf library, which allows me to convert HTML to PDF. If you&apos ...

Is there really a need to go through the hassle of creating a pure javascript/jquery widget when I can simply load it into an

Previously, I had a widget with the following code: <script src="http://www.mywebsite.com/widget/widget.js?type=normal" type="text/javascript"></script> <div id="archie-container"></div> This widget checked for the presence of jQu ...

The search and sorting functionality in jquery DataTables is malfunctioning

I am facing difficulties with sorting and filtering the datatable as none of the JS functions seem to be working properly. I have already included the necessary JS files. Here are some details: I am connecting to a database to retrieve data in JSON format. ...

The implementation of various asynchronous Html.BeginForm scripts

I have created a webpage showcasing various products along with their details. The plan is for the details to be displayed when a button is clicked. I used a foreach loop to generate tables containing the products and a link to view more details. However, ...

Addressing three visual problems with an html form input, dropdown menu, and clickable button

Currently, the output of my code looks like this: https://i.stack.imgur.com/pl5CJ.jpg The first box (squared) represents an <input>, while the second box (rectangled) is a <select>. There are several issues that I am facing: The text entered ...

Is there a way to extract the URL from an ng-resource?

Is there a way to retrieve the URL and parameters from an ng-resource object? If not, what are some strategies for creating a custom wrapper or extending ng-resource to achieve this functionality? Update: My goal is to extract the URL and params from the ...

Implement the Vue.js @click directive in a location outside of an HTML element

I've set up a link like this: <a href="#" @click="modal=true">Open modal</a> Here's the data setup: export default { data () { return { modal: false } } } Is there a way to trigger the cli ...

Instructions for incorporating animation into the CSS properties of an element as the class is updated using jQuery

The issue: I am facing a challenge with an HTML element that has a class called hidden which hides the element with the css attribute display: none;. When I use JavaScript to remove the class, the element immediately becomes visible again (the original di ...

Having trouble with refreshing the div content when using jQuery's $.ajax() function

My goal is to refresh a div that has the id #todos after saving data in the database. I attempted to use .load() within $.ajax() $('.todo--checkbox').change(function () { let value = $(this).data('value'); $.ajax({ url: ...

Struggling to eliminate buttons upon clicking, but they persistently reappear (JavaScript, HTML)

I have encountered an issue with buttons in my table that I am struggling to resolve. Each row in the table contains a "Pack" action button, which when clicked, is removed to prevent accidental double-packing of items. Everything was functioning smoothly ...

Finding a particular movie in React

import { useState,useEffect } from 'react' import React from 'react' import MoviesItem from './MoviesItem' const Movies = ({search}) => { const [movie, setMovie] = useState([]) const fetchData = async() => ...

Library for implementing stylish font effects in JavaScript

I remember stumbling upon a unique JavaScript library that enabled users to write text in different styles and formats. Unfortunately, I am having trouble finding it again. Can anyone suggest any helpful links? Thank you, Murtaza ...

Discovering the highest value within an array of objects

I have a collection of peaks in the following format: peaks = 0: {intervalId: 7, time: 1520290800000, value: 54.95125000000001} 1: {intervalId: 7, time: 1520377200000, value: 49.01083333333333} and so on. I am looking to determine the peak with the hig ...

Error: The function onChange is not recognized

I've been struggling to update the state value of a parent component from a child component, but I keep running into an error that says onChange is not a function. Despite trying various solutions that I came across, nothing seems to be working. Here ...

Determine the number of elements chosen within a complex JSON structure

I need to figure out how to count the length of a jsonArray, but I'm stuck. Here's an example to start with: https://jsfiddle.net/vuqcopm7/13/ In summary, if you click on an item in the list, such as "asd1", it will create an input text every t ...

Error in Dotfuscator - External type System.Data.Entity.Infrastructure.Annotations.AnnotationValues not located for EntityFramework framework with Version 6.0.0.0

I am looking to encrypt my *.exe file along with its dependencies. I encountered the following issue: External type not found System.Data.Entity.Infrastructure.Annotations.AnnotationValues,EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken= ...