[Simple Way]-How To Get Data From Database Using JQuery Ajax In Asp Net MVC


In the previous article, we discussed how to perform Insert, Update, and Delete operations using jQuery Ajax and Modal Popup in ASP.NET MVC. In this post, we will focus on accessing and displaying data from the database using Ajax and jQuery in ASP.NET MVC. We will demonstrate how to retrieve a list of customers from the MVC controller and display it in an HTML table using jQuery Ajax.

Let's begin by creating a basic view that presents the list of customers in an HTML table. We will fetch the data from the database and showcase it on the HTML page using Ajax and jQuery.

How to get data from controller using ajax

We can divide this task into to below step

  1. Creating New ASP.NET MVC Project in VS
  2. Creating Database Table for showing list
  3. Adding EntityFramework for communicating with database
  4. Creating Controller for returning view
  5. Adding View from Action Method
  6. Run your Project

Customerlist

Step 1: Creating New ASP.NET MVC Project in VS

Open Visual and add a empty MVC project

Step 2:Creating Database Table for showing list

Let's create the database table to showcase the list using Ajax. I have designed a table named TblCustomer with columns Id, Name, ContactNumber, Address, and City. Below is the SQL script for creating this table, which you can utilize for practice purposes.

CREATE TABLE [dbo].[TblCustomer](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](max) NULL,
	[ContactNumber] [nvarchar](max) NULL,
	[Adress] [nvarchar](max) NULL,
	[City] [nvarchar](max) NULL,
    CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

TblCustomer

Step 3: Adding EntityFramework for communicating with database

  • Follow the below step and image diagram
  • Right-click on the Model folder and select add a new item
  • Click on the Data option on the left side menu
  • select the Ado .net entity data model from the option
  • Follow the below step

Add Entity Framework_1

Add entity framework_2

If you follow the below step then it create entity data model in our project.

Entity Data Model

Step 4: Creating Controller for returning view

Now, let's add a controller to our project to display the list. Right-click on the Controller folder within the project, then select "Add" followed by "Controller", and choose "Empty Controller".Create a Controller

I have added a HomeController in our project.

AddedController

Now, let's write the logic in our HomeController.cs. Open HomeController.cs and add the following action methods. Here, I am going to add one action method to our controller which retrieves all customers from the TblCustomer Table.

HomeController.cs

using GetDataAjax.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GetDataAjax.Controllers
{
public class HomeController : Controller
    {
// GET: Home
public ActionResult Index()
        {
return View();
        }
public ActionResult GetCustomerList()
        {

            SampleRestApiEntities db = new SampleRestApiEntities();
var customerlist = db.TblCustomers.ToList();
return Json(customerlist, JsonRequestBehavior.AllowGet);
        }
    }
}

Step 4: Adding View from Action Method

Now Right-click on Index Action Method in HomeController, add empty View, please make sure to click the “Use a Layout page” option. it will create the layout and css for our project.

addview

 

AddIndexView-1

Now Open Index.cshtml and  write  the below code

How to get a list from mvc controller to view using jquery Ajax

I have crated simple view, in which i have taken a HTML table.now using Ajax we are fetching the list from Mvc Controller and then we are showing the list in view.

Index.cshtml


@{
    ViewBag.Title = "Index";
}

<title> Use of JQuery to Add Edit Delete Table Row </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<h2>Index</h2>
<div class="container">
    <h1>How to get data from database using jquery ajax in asp net MVC </h1>
    <br />
    <fieldset>
        <legend>
            Customer List
        </legend>
        <table class="table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>ContactNumber</th>
                    <th>Address</th>
                    <th>City</th>
                </tr>
            </thead>
            <tbody id="tblbody">
            </tbody>
        </table>
    </fieldset>
</div>
<script type="text/javascript">
//Load Data in Table when documents is ready
    $(document).ready(function () {
        BindpatientData();
    });
    function BindpatientData() {
        $.ajax({
            url: "/Home/GetCustomerList",
            type: "GET",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: function (result)
            {
                debugger;
if (result) {
//itetrate thorugh each record and bind it to td
var html = '';
                    $.each(result, function (key, item) {
var tablerow = '<tr>'
                            + '<td>' + item.Id + '</td>' 
                            + '<td>' + item.Name + '</td>' 
                            + '<td>' + item.ContactNumber + '</td>' 
                            + '<td>' + item.Adress + '</td>' 
                            + '<td>' + item.City + '</td>'
                            +'</tr>';
                        $("#tblbody").append(tablerow);
                    });
                }
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
    }
</script> 

As you can see, I'm using AJAX to call our controller's action method, GetCustomerList(). Upon receiving a successful result, I iterate through the customer list and append rows to the table.

  • BindpatientData(): This function is called when the document is ready, initiating the data binding process.
  • $.ajax({ ... }):  jQuery AJAX call to fetch data from the server.
  • url: "/Home/GetCustomerList": Specifies the URL of the controller action method responsible for retrieving the customer list.
  • success: function (result) { ... }: This function is executed if the AJAX call is successful. It iterates through the received data and constructs table rows (<tr>) containing customer details, which are then appended to the table body (#tblbody).

Fetches customer data from the server and dynamically populates an HTML table with the retrieved data.

Step:6 Run your Project

Customerlist

*Thank you so much if you have a question please comment

Some Concept of AJAX Request

When we use Promise Concept with AJAX Request, then we get the full idea of ​​ Promise Concepts. Because the response we get when the AJAX request is fired, is not received immediately, but after the request is completely performed, that is, some time elapses between the request and the response and the response we receive is a Future Point. whereas we have no idea of ​​how much time will elapse between sending the request to receiving the response.

jQuery’s Deferred Object is actually an implementation of the Promise Interface itself. It not only provides all the features of Promise, it also allows us to create new Deferred Objects and attach Future Handlers with those Deferred Objects and resolve them programmatically.

 

That is, the Deferred Object that returns from this AJAX call is based on the implementation of the Promise Interface. Since it is a Promise Object, we can attach to it Handlers that invoke Future Handlers based on the Deferred Object that is returned after the AJAX request is completed.

Not only this, as we can see in the above example code that we can also add new Future Handlers later based on our need, as in the last line of the previous code segment using the done() method with myAJAXRequest object. By doing this the new function has been queued.

If the jQuery interpreter does not reach this code until the AJAX call is completed, then this function would be queued to be executed later. Whereas if the AJAX call is completed by reaching this code, then in that case this function gets executed immediately. These coding approaches provide us with a lot of flexibility to write such codes, which are executed later depending on the need or situation.

Promise is an object that represents a one-time event and is usually created by an asynchronous task such as AJAX.

At first glance, the “Promise” object represents the pending status of a task, which is later either resolved or rejected.

If the task is resolved, it means that the task is completed or done, while if the task fails, the promise object is rejected.

Once a Promise Object is Resolve or Rejected, then that Object remains in that Web Page in the same Resolved or Rejected state forever. Also, the callbacks of this Promise Object do not fire again till the life time of the current web page.

We can also attach a Callback Function to a Promise Object, which fires when the Promise Object is resolved or rejected.

Also we can add new Callback Functions whenever we want with this Promise Object. Even if that Promise Object has already been Resolve or Rejected.

Whereas the Callback Function to be added in case the Promise Object is Resolve or Rejected, also runs immediately as soon as the Promise Object is added to the Queue.

Also, we can also logically combine Promises with other new Promises. Which allows us to write codes that say that

“When all these specified work is done, then do this work.”

Deferred Object is a Chainable Utility Object, which is created using the jQuery.Deferred() Function. This Object can register Multiple Callback Functions in Callback Queues, Invoke Callback Queues and Relay Success or Failure State of any Synchronous or Asynchronous Callback Function to other Callback Function.

Deferred objects are chainable just like any other jQuery object, but each deferred object has its own methods. After creating a Deferred Object, we can use it through Chaining to meet different types of Deferred Methods or by storing the reference of Created Deferred Object in a Variable and use that Variable.