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#
- Simple Way Find and replace text in Word document using C#
- Implementing “Remember Me” Feature in ASP.NET MVC
- [Solved]-Cookie loses value when page is changed in MVC
- How to post File Upload and other form fields to one action Asp .Net MVC C#
- How To Post File and Data to API using HttpClient C#
- Create ASP.NET Core Web API Without Entity Framework
- .NET Core Web API Using Code First Entity Framework Approach
- Create Asp.Net Core Web Api Using Entity Framework Database First
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- CRUD operation using partial view in MVC with modal popup
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- Crud Operations in MVC Without Entity Framework
- Create Login,Signout and Registration in Asp .Net Mvc Using Entity
- Export Gridview to Excel and Csv in Asp .Net With Formatting Using c#
- How to Display Binary Image in Gridview from Database in Asp .Net c#
- [Solved]-How to Upload pdf file using jquery MVC?
- [Solved]-Uploading both data and files in FormData using Ajax MVC
- C# -Saving a base64 string as an image into a folder on server in Web Api
- [Solved]-Download pdf file from link and save in local file folder in Asp .Net
- [Solved]-Delete Files older than X Months,Days,Minute in a Directory- C# .NET
- [Solved]-LEFT OUTER JOIN in LINQ With Where clause in C#
- INNER JOIN,RIGHT JOIN,LEFT JOIN USING LINQ IN Multiple Table C#
- [Solved]-Convert Base64 To Image And Save in folder and Display it- C#
- [Solved]-How to Overlay Two Images in .NET-C#
- How to Create Multilingual Website in Asp .Net
- C# – How to add double quotes to a string that is inside a variable
- Update an Image with Upload Button For Each Row in Gridview-Asp .Net
- How to Bind Data in DataList Control in Asp.Net – C#
- Upload and Display an Image in Gridview From Image Path in Database -C#