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
- Creating New ASP.NET MVC Project in VS
- Creating Database Table for showing list
- Adding EntityFramework for communicating with database
- Creating Controller for returning view
- Adding View from Action Method
- Run your Project
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
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
If you follow the below step then it create entity data model in our project.
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.
I have added a HomeController in our project.
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.
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
*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.
The post [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- How To Post Multiple Objects from View To dot net core 6 MVC Controller using ajax jquery
- ASP NET Core MVC how to display data from SQL table in List Razor Template by UserID foreign key
- how to just get date without getting time when you retrieve data from database in asp.net mvc
- How to insert data into a database using jQuery / Ajax in ASP.NET MVC?
- How get data from database column as a heading using Repeater in ASP.NET
- How to get the xml data from c# and show it as list in html using jquery
- How to load image from database using jquery ajax in asp.net
- Display image file from database using Entities Asp Net MVC C#
- how to bind data to select2 jquery from database in mvc
- how to bind data from database to select tag of html using jquery
- How get the names of all the tables from a database in a combo box using c#
- How to get XML from Ajax jQuery Instead of json
- How to send data from c++ application to dot net core app using Named pipeline
- How to get JSON data directly from the database table?
- How to Redirect and post a collection of data to destination URL and redirect to that external URL in MVC c# without using Ajax or client side
- How to get object from database using ADO.NET?
- how to Get by Id data from database Blazor C#
- How to get all data from API using objects with Newtonsoft.Json and I receive wrong data in xamarin c#
- How to add data from database into pins using xamarin.forms.maps android
- How to Retrieve Data from Oracle Database using ML.NET's DatabaseSource Class
- Pass data from view to controller using AJAX in C# ASP.NET Core MVC
- how attach multiple file in using file upload in asp.net mvc using jquery ajax
- How can i insert data from a table row into Database on clicking a button in the row in C# MVC
- How can i insert data from a table row into Database on clicking a button in the row in C# MVC
- How can i hide the query string from the url using asp. Net mvc
- How to Get Data from controller with ajax c#
- How to send multiple image from MVC view to controller using Ajax in array format?
- How to get data remotely from mySQL database installed in raspberry pi in WinForms application?
- Pass data from view to controller using ajax in ASP.NET MVC
- How to pass data from the View textbox to Controller using ASP.NET MVC
- GC.Collect() in Dispose in simple class
- Inserting Data in Object with Hard Coded Form in ASP.Net MVC
- System Level File.Encrypt method
- Cant use Android Emulator in Visual Studio with Windows 7
- Operation that is opened to REST consumers only
- C# MissingMethodException: Constructor on type 'System.Int32' not found
- WCF restful application PUT, POST, DELETE receive the same error: "the method is not allowed."
- core utilisation in c#
- I can't combine 2 linq queries into one return. How can I do it?
- Reading to an Excel file
- SQL returning incorrect amount of rows
- Adding blank space as one of my variable
- How to force extenal library to use SQL transaction
- How to get a list to correctly count the total number of int in Unity
- Decryption-Only method in C#
- How to read and write DataGridView data to Sql Table
- Discrepancy between C# MD5 and Objective C MD5
- NullReferenceException error in Unity
- Issues with JustMock and Large Test Runs
- How can I perform a DragDrop/swap of a ChartControl?