Customerlist

[Simple Way]-How to get data from database using JQuery Ajax in asp net MVC

In the previous article, we have discussed Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc,In this post, We will discuss how we can access and display the data from the database using ajax jquery asp.net MVC. so we will show you How to get a list from the MVC controller to view using jquery ajax.

So Let’s start, step by step learn We will create a basic view that shows the list of customers in the HTML table.

We will fetch the data from the database and display 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, for showing the list using ajax. I have created a table called TblCustomer with column Id, Name, ContactNumber, Adress, City. You can find the SQL Script of the table you can use 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 in our project for showing the list, Right-click on the Controller folder in the project =>add an 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 returns all customer in 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 in I’m making ajax for calling our controller ActionMethod GetCustomerList(). After getting the successful result, I’m iterating through the customer list and appending the row in the table.

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.

Ashok Patel

I'm a software engineer, having good experience in software programming web designing with great command on ASP.NET, React JS, Angular JS,.NET Core HTML5, JavaScript, T-SQL, JQuery.
Also have great experience in Electronics and electrical engineers design.
I like to do RND and Research.

Your Header Sidebar area is currently empty. Hurry up and add some widgets.