Get Multiple Table In View Using AJAX In ASP.NET MVC

Introduction

 
In this article, I will explain how you can display multiple tables in a view using Ajax with asp.net MVC. Here I will create Ajax calls for multiple tables. For this article, you should have a basic understating of following
  • Bootstrap 4
  • JQuery Data Table
  • Ajax
  • MVC
  • Entity Framework
  • View Model
  • SQL Server
Step 1
 
Open your favourite SQL server database -- any version. It doesn’t really matter. Create tables’ customer product, Order and OrderItem.
  1. CREATE TABLE [dbo].[Customer](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [FirstName] [nvarchar](40) NOT NULL,  
  4.     [LastName] [nvarchar](40) NOT NULL,  
  5.     [City] [nvarchar](40) NULL,  
  6.     [Country] [nvarchar](40) NULL,  
  7.     [Phone] [nvarchar](20) NULL,  
  8.  CONSTRAINT [PK_CUSTOMER] PRIMARY KEY CLUSTERED   
  9. (  
  10.     [Id] ASC  
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  12. ON [PRIMARY]  
  13.   
  14. GO  
  15.   
  16. CREATE TABLE [dbo].[Product](  
  17.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  18.     [ProductName] [nvarchar](50) NOT NULL,  
  19.     [SupplierId] [intNOT NULL,  
  20.     [UnitPrice] [decimal](12, 2) NULL DEFAULT ((0)),  
  21.     [Package] [nvarchar](30) NULL,  
  22.     [IsDiscontinued] [bitNOT NULL DEFAULT ((0)),  
  23.  CONSTRAINT [PK_PRODUCT] PRIMARY KEY CLUSTERED   
  24. (  
  25.     [Id] ASC  
  26. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  27. ON [PRIMARY]  
  28.   
  29. GO  
  30.   
  31. ALTER TABLE [dbo].[Product]  WITH CHECK ADD  CONSTRAINT [FK_PRODUCT_REFERENCE_SUPPLIER] FOREIGN KEY([SupplierId])  
  32. REFERENCES [dbo].[Supplier] ([Id])  
  33. GO  
  34.   
  35. ALTER TABLE [dbo].[Product] CHECK CONSTRAINT [FK_PRODUCT_REFERENCE_SUPPLIER]  
  36. GO  
  37.   
  38.   
  39. CREATE TABLE [dbo].[Order](  
  40.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  41.     [OrderDate] [nvarchar](50) NOT NULL CONSTRAINT [DF__Order__OrderDate__25869641]  DEFAULT (getdate()),  
  42.     [OrderNumber] [nvarchar](10) NULL,  
  43.     [CustomerId] [intNOT NULL,  
  44.     [TotalAmount] [decimal](12, 2) NULL CONSTRAINT [DF__Order__TotalAmou__267ABA7A]  DEFAULT ((0)),  
  45.  CONSTRAINT [PK_ORDER] PRIMARY KEY CLUSTERED   
  46. (  
  47.     [Id] ASC  
  48. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  49. ON [PRIMARY]  
  50.   
  51. GO  
  52.   
  53. ALTER TABLE [dbo].[Order]  WITH CHECK ADD  CONSTRAINT [FK_ORDER_REFERENCE_CUSTOMER] FOREIGN KEY([CustomerId])  
  54. REFERENCES [dbo].[Customer] ([Id])  
  55. GO  
  56.   
  57. ALTER TABLE [dbo].[OrderCHECK CONSTRAINT [FK_ORDER_REFERENCE_CUSTOMER]  
  58. GO  
  59.   
  60. CREATE TABLE [dbo].[OrderItem](  
  61.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  62.     [OrderId] [intNOT NULL,  
  63.     [ProductId] [intNOT NULL,  
  64.     [UnitPrice] [decimal](12, 2) NOT NULL DEFAULT ((0)),  
  65.     [Quantity] [intNOT NULL DEFAULT ((1)),  
  66.  CONSTRAINT [PK_ORDERITEM] PRIMARY KEY CLUSTERED   
  67. (  
  68.     [Id] ASC  
  69. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  70. ON [PRIMARY]  
  71.   
  72. GO  
  73.   
  74. ALTER TABLE [dbo].[OrderItem]  WITH CHECK ADD  CONSTRAINT [FK_ORDERITE_REFERENCE_ORDER] FOREIGN KEY([OrderId])  
  75. REFERENCES [dbo].[Order] ([Id])  
  76. GO  
  77.   
  78. ALTER TABLE [dbo].[OrderItem] CHECK CONSTRAINT [FK_ORDERITE_REFERENCE_ORDER]  
  79. GO  
  80.   
  81. ALTER TABLE [dbo].[OrderItem]  WITH CHECK ADD  CONSTRAINT [FK_ORDERITE_REFERENCE_PRODUCT] FOREIGN KEY([ProductId])  
  82. REFERENCES [dbo].[Product] ([Id])  
  83. GO  
  84.   
  85. ALTER TABLE [dbo].[OrderItem] CHECK CONSTRAINT [FK_ORDERITE_REFERENCE_PRODUCT]  
  86. GO   
Step 2 
 
Now open your favorite Visual Studio 2017 or any version you wish to.
 
 
Step 3
 
Create an empty project in Visual Studio and give an appropriate name. Checked MVC checkbox and click on OK.
 
 
Step 4
 
Right-click on the Models folder and add a database model. Add Entity Framework now. For that, right-click on Models folder, select Add, then select New Item.
 
 
You will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name MyModel (this name is not mandatory, you can give any name) and click "Add"
 
 
After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".
 
 
After clicking on "Next", a window will appear. Choose New Connection. Another window will appear. Add your server name - if it is local, then enter a dot (.). Choose your database and click "OK".
 
 
The connection will be added. If you wish, save the connection name as you want. You can change the name of your connection below. It will save the connection in the web config. Now, click "Next".
 
 
After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".
 
 
Entity Framework gets added and the respective class gets generated under the Models folder.
 
 
Step 5 
 
Right-click on Controllers folder and add a controller.
 
 
A window will appear. Choose MVC5 Controller-Empty and click "Add".
 
 
After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home.
 
 
Controller Class Code
  1. using DisplayMultipleTableAjax_Demo.Models;  
  2. using System.Linq;  
  3. using System.Web.Mvc;  
  4.   
  5. namespace DisplayMultipleTableAjax_Demo.Controllers  
  6. {  
  7.     public class HomeController : Controller  
  8.     {  
  9.         private readonly SampleDBContext db = new SampleDBContext();  
  10.   
  11.         public ActionResult Index()  
  12.         {  
  13.             return View();  
  14.         }  
  15.   
  16.         public ActionResult DataTable()  
  17.         {  
  18.             return View();  
  19.         }  
  20.   
  21.         public JsonResult GetCustomers()  
  22.         {  
  23.             db.Configuration.ProxyCreationEnabled = false;  
  24.             var customers = db.Customers.ToList();  
  25.             return Json(new { data = customers }, JsonRequestBehavior.AllowGet);  
  26.         }  
  27.           
  28.         public JsonResult GetProducts()  
  29.         {  
  30.             db.Configuration.ProxyCreationEnabled = false;  
  31.             var orders = db.Products.ToList();  
  32.             return Json(new { data = orders }, JsonRequestBehavior.AllowGet);  
  33.         }  
  34.   
  35.         public JsonResult GetOrders()  
  36.         {  
  37.             db.Configuration.ProxyCreationEnabled = false;  
  38.             var orders = db.Orders.ToList();  
  39.             return Json(new { data = orders }, JsonRequestBehavior.AllowGet);  
  40.         }  
  41.   
  42.         public JsonResult GetOrderItem()  
  43.         {  
  44.             db.Configuration.ProxyCreationEnabled = false;  
  45.             var orders = db.OrderItems.ToList();  
  46.             return Json(new { data = orders }, JsonRequestBehavior.AllowGet);  
  47.         }  
  48.     }  
  49. }  
Step 6
 
Right click on Index action method in controller class “Add View”
 
 
 
Index View Code
  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4. <link href="@Url.Content("~/Content/DataTables/css/dataTables.bootstrap4.min.css")" rel="stylesheet" />  
  5.   
  6. <ul class="nav nav-pills">  
  7.     <li class="nav-item">  
  8.         <a class="nav-link active" data-toggle="pill" href="#home">Customers</a>  
  9.     </li>  
  10.     <li class="nav-item">  
  11.         <a class="nav-link" data-toggle="pill" href="#menu1">Products</a>  
  12.     </li>  
  13.     <li class="nav-item">  
  14.         <a class="nav-link" data-toggle="pill" href="#menu2">Order</a>  
  15.     </li>  
  16.     <li class="nav-item">  
  17.         <a class="nav-link" data-toggle="pill" href="#menu3">Order Items</a>  
  18.     </li>  
  19. </ul>  
  20.   
  21. <div class="tab-content">  
  22.     <div class="tab-pane container active p-0" id="home" style="margin-top:15px;">  
  23.         <table id="cutomerTable" class="table table-bordered">  
  24.             <thead class="thead-dark text-white">  
  25.                 <tr>  
  26.                     <th>First Name</th>  
  27.                     <th>Last Name</th>  
  28.                     <th>City</th>  
  29.                     <th>Country</th>  
  30.                     <th>Phone</th>  
  31.                 </tr>  
  32.             </thead>  
  33.             <tbody></tbody>  
  34.         </table>  
  35.     </div>  
  36.     <div class="tab-pane container p-0" id="menu1" style="margin-top:15px;">  
  37.         <table id="productTable" class="table table-bordered" style="width:100%;">  
  38.             <thead class="thead-dark text-white">  
  39.                 <tr>  
  40.                     <th>Product Name</th>  
  41.                     <th>Supplier Id</th>  
  42.                     <th>Unit Price</th>  
  43.                     <th>Package</th>  
  44.                     <th>Is Discontinued</th>  
  45.                 </tr>  
  46.             </thead>  
  47.             <tbody></tbody>  
  48.         </table>  
  49.     </div>  
  50.     <div class="tab-pane container fade p-0" id="menu2" style="margin-top:15px;">  
  51.         <table id="orderTable" class="table table-bordered" style="width:100%;">  
  52.             <thead class="thead-dark text-white">  
  53.                 <tr>  
  54.                     <th>Order Date</th>  
  55.                     <th>Order Number</th>  
  56.                     <th>Customer Id</th>  
  57.                     <th>Total Amount</th>  
  58.                 </tr>  
  59.             </thead>  
  60.             <tbody></tbody>  
  61.         </table>  
  62.     </div>  
  63.     <div class="tab-pane container fade p-0" id="menu3" style="margin-top:15px;">  
  64.         <table id="orderItemTable" class="table table-bordered" style="width:100%;">  
  65.             <thead class="thead-dark text-white">  
  66.                 <tr>  
  67.                     <th>Order Id</th>  
  68.                     <th>Product Id</th>  
  69.                     <th>Unit Price</th>  
  70.                     <th>Quantity</th>  
  71.                 </tr>  
  72.             </thead>  
  73.             <tbody></tbody>  
  74.         </table>  
  75.     </div>  
  76. </div>  
  77. <script src="@Url.Content("~/Scripts/jquery-3.4.1.min.js")"></script>  
  78. <script src="@Url.Content("~/Scripts/DataTables/jquery.dataTables.min.js")"></script>  
  79. <script src="@Url.Content("~/Scripts/DataTables/dataTables.bootstrap4.min.js")"></script>  
  80. <script type="text/javascript">  
  81.     $(document).ready(function () {  
  82.         $("#cutomerTable").DataTable({  
  83.             "ajax": {  
  84.                 "url""@Url.Action("GetCustomers", "Home")",  
  85.                 "type""GET",  
  86.                 "datatype""json"  
  87.             },  
  88.             "columns": [  
  89.                 { "data""FirstName" },  
  90.                 { "data""LastName" },  
  91.                 { "data""City" },  
  92.                 { "data""Country" },  
  93.                 { "data""Phone" }  
  94.             ]  
  95.         });  
  96.         //Product Table   
  97.         $("#productTable").DataTable({  
  98.             "ajax": {  
  99.                 "url""@Url.Action("GetProducts", "Home")",  
  100.                 "type""GET",  
  101.                 "datatype""json"  
  102.             },  
  103.             "columns": [  
  104.                 { "data""ProductName" },  
  105.                 { "data""SupplierId" },  
  106.                 { "data""UnitPrice" },  
  107.                 { "data""Package" },  
  108.                 { "data""IsDiscontinued" },  
  109.             ]  
  110.         });  
  111.         //Order Table   
  112.         $("#orderTable").DataTable({  
  113.             "ajax": {  
  114.                 "url""@Url.Action("GetOrders", "Home")",  
  115.                 "type""GET",  
  116.                 "datatype""json"  
  117.             },  
  118.             "columns": [  
  119.                 { "data""OrderDate" },  
  120.                 { "data""OrderNumber" },  
  121.                 { "data""CustomerId" },  
  122.                 { "data""TotalAmount" }  
  123.             ]  
  124.         });  
  125.         //Order Item  
  126.         $("#orderItemTable").DataTable({  
  127.             "ajax": {  
  128.                 "url""@Url.Action("GetOrderItem", "Home")",  
  129.                 "type""GET",  
  130.                 "datatype""json"  
  131.             },  
  132.             "columns": [  
  133.                 { "data""OrderId" },  
  134.                 { "data""ProductId" },  
  135.                 { "data""UnitPrice" },  
  136.                 { "data""Quantity" }  
  137.             ]  
  138.         });  
  139.     });  
  140. </script>  
Step 7
 
Install the latest version of bootstrap and JQuery and JQuery data table from NuGet package manager under tools in Visual Studio.
 
Step 8
 
Build your project and Run by pressing Ctrl+F5