Having issues with populating Gridview using AJAX post method? Looking for a solution?

Having trouble displaying data from a SQL database in a GridView on a webpage using AJAX post method? You're not alone. Many face the same issue of the grid appearing empty despite fetching data from the database.

If you want to populate your GridView with data upon button click, consider revisiting your code and make sure you are correctly binding the data fetched through AJAX post method.

// C# code
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindDummyRow();
    }
}

private void BindDummyRow()
{
    // Create dummy DataTable for GridView
}

[WebMethod]
public static string GetCarService()
{
    // Fetch Car Service data from the database
}

// JavaScript code
function GridDisplay(){
    GetCarService();
}

// More JavaScript code...

// ASPX markup
<asp:Button runat="server" ID="modalTransportSearchButton" Text="Search" OnClientClick="GridDisplay();" Width="100px" />

// The rest of the GridView markup here...

Answer №1

If you want your response data in JSON format, set the datatype to json. Here is an example:

 public class Cars
    {
        public string CarServiceId;
        public string CarServiceName;
        public string Contact1;
        ........
    }

Your web method should return a list of car class like this:

   [WebMethod]
    public List<Cars> getListOfCars(List<string> aData)
    {
        SqlDataReader dr;
        List<Cars> carList = new List<Cars>();
     
        using (SqlConnection con = new SqlConnection(conn))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "YourStoredProcedureName";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = con;
                con.Open();
                dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        string CarServiceId= dr["CarServiceId"].ToString();
                        string CarServiceName= dr["CarServiceName"].ToString();
                        string Contact1= dr["Contact1"].ToString();
     
                        carList.Add(new Cars
                              {
                                CarServiceId= CarServiceId,
                                 CarServiceName= CarServiceName,
                                 Contact1= Contact1
                            });
                    }
                }
            }
        }
        return carList;
    }

In JQuery, your success function should look something like this:

function OnSuccess(response) {
 var aData=response.d
  alert(aData);
}

Use $.each() to loop through and set data to your gridview control, which essentially converts it to an HTML table. Here's an example:

 function OnSuccess(response) {
    var aData = response.d
    var fragmentation = "";
    $(aData).each(function (indx,val) {
        console.log(val.CarServiceId);
        fragmentation += "<tr><td>" + val.CarServiceId + "</td><td>" + val.CarServiceName + "</td><td>" + val.Contact1 + "</td></tr>"
    });
    $(".myGrdivewClassName").append(fragmentation);
}

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

What is the process for including a class on a div element?

I have written a code that displays a series of images in a sequence. Once the last image appears, I want to switch the class from .d-none to .d-block on the div Can this be achieved? onload = function startAnimation() { var frames = document.getE ...

Enhance the readability and writability of the properties of JavaScript objects

I'm curious if there's a way to make existing properties of JavaScript objects immutable after they've been assigned. Essentially, what I want is to lock in the current properties of an object but still allow new ones to be added. Can exis ...

When you click on a single checkbox, it automatically selects all of them

Struggling with a form that uses HTML PDO and AngularJS for validation. When clicking one checkbox, all other checkboxes get checked as well. Here is my form: <input type="checkbox" name="declaration" id="declaration" ng-m ...

Visualizing Data with Flot.js - A Comprehensive Guide

Does anyone know how to organize values in a flot histogram by day, merging them into one bar per day? I've been searching for a solution but can't seem to find one. __ If you have any ideas, please share! ...

Changing the color of a div through animation

Similar Question: jQuery animate backgroundColor I am looking to make a div shine or switch colors to signal to someone that they have gotten a message. What is the best way to animate the background color of a div for this purpose? ...

Best practices for executing an asynchronous forEachOf function within a waterfall function

I've been working with the async library in express js and I'm encountering an issue when using two of the methods alongside callbacks. The variable result3 prints perfectly at the end of the waterfall within its scope. However, when attempting t ...

Issue with Jest Test Trigger Event Not Invoking Method

Currently, I am in the process of writing tests for my Vue application. One particular test involves a button that triggers a logout function. The goal is to determine if the function is executed when the button is clicked. Initially, I attempted to mock ...

Troubleshooting: xPages radio button group onchange event malfunctioning

I have created a simple page with a listbox control that should update its values based on the selection made in a radiobutton group. The listbox is connected to a scope variable array as its data source. However, I am experiencing an issue where the lis ...

Can anyone recommend a super sleek drop-down navigation menu that includes both images and text descriptions?

My interest has been piqued on how to create a menu similar to the one on with all the images and text details. Does anyone have any insights on the technologies utilized for this? Are there any commercial options available that offer a similar functiona ...

Fixing a JavaScript Issue with Updating Div Class Content

When attempting to replace HTML content within a specific class, everything seems to work fine with simple code like <p>0</p>. However, when trying to input more complex code such as: $('.festi-cart-menu-item').html('<a id=" ...

A step-by-step guide on resolving the issue "Error: listen EADDRINUSE: address already in use :::5000" in the event of an error

node:events:495 throw er; // Unhandled 'error' event ^ Error: listen EADDRINUSE: address already in use :::5000 at Server.setupListenHandle [as _listen2] (node:net:1817:16) at listenInCluster (node:net:1865:12) at Server. ...

An issue has been discovered with the Search function as JavaScript's Array.filter() and .map() methods are not functioning properly, resulting in

Currently, I'm working on integrating a search feature into my Flask application that will display the cities entered by users and are present in the JSON API results of a weather API. I am following a tutorial and have used a code similar to this: h ...

The functionality of .bind() is malfunctioning on both Microsoft Edge and Google Chrome browsers

Everything seems to be running smoothly on Mozilla (version 103.0), but unfortunately, it's not performing as expected on Chrome or Microsoft Edge. $('#loading').bind('ajaxStart', function () { $(this).show(); }).bind('ajaxS ...

PHP: Dynamically update div content upon submission

I am attempting to update the "refresh" div after clicking the Submit button and also at regular intervals of 5 seconds. Despite looking through various resources, I have not been able to find a solution that meets my requirements. <script src="h ...

After refreshing the page in Next JS, there is a delay in loading the Swiper Js styles. The Swiper slides appear stretched while waiting for Next JS to load the styles. Any suggestions

Having an issue with my Next 14.0.3 app and tailwind CSS. I recently installed swiper JS version 11.0.5 using npm. The problem arises when I reload the page, it takes about 1 or 2 seconds for the swiper styles to load. During this time, the swiper slides s ...

Transforming 2D rotation into 3D using three.js

I stumbled upon a fascinating snippet that allows elements to rotate around another element, mimicking planetary rotation. I'm eager to incorporate this 2D rotation feature into a three.js project for a more immersive 3D experience. The demo showcasi ...

Exploring the Variations in Selenium WebDriver Implementations

In my recent experience, I created a sample test in Selenium using the IE WebDriver, which worked perfectly on the IE browser. However, when I tried running the same test on Chrome or Firefox by simply changing the driver to Chrome or Firefox Driver, the t ...

retrieving the value of a textbox generated dynamically through C# code

This is the starting point of my page: protected void Page_Load(object sender, EventArgs e) { Table table = this.GetTable(); PlaceHolder1.Controls.Add(table); } private Table GetTable() { // Create a table with specific properties var tabl ...

Searching for an item within an object to retrieve an alternative element from that very same object

I am currently working on a task that involves checking the data headers to see if they contain 'accept=application/xml', and only then returning the body in XML format. Below is the dataset: [ { url: '/a', status: '200&apos ...

Conceptual Confusion

Create a unique function using the array provided below to find and store the longest name. Then, save that name in a variable called longest_name and print it out using another variable named answer. let array = [ "John", "Lee", "Smitty", "Cyren", "Linda" ...