This article gives an overview of how to use jQuery datatable in MVC to perform single column search in jQuery Ajax. I will use jQuery datatable plugin in this demo application and explain how to apply single column search. Here is the
code.
This is final output of the application.
This example requires the following basic understanding
- JQuery datatable
- Ajax
- Bootstrap
- Entity framework
- MVC
Step 1
There are multiple ways to create a new project in Visual Studio 2019. When you first open Visual Studio, the start window appears, and from there, you can choose to create a new project.
If the Visual Studio development environment is already open, you can create a new project by choosing File > New > Project on the menu bar or by clicking the New Project button on the toolbar.
Step 2
On the Create a new project page, a list of your recently selected templates appears on the left. The templates are sorted by most recently used.
If you're not selecting from the recently used templates, you can filter all available project templates by Language (for example, C#), Platform (for example, Windows or Azure), and Project type (for example, Desktop or Web). You can also enter search text into the search box to further filter the templates, for example, asp.net.
Select a template and then click Next.
Step 3
The Configure your new project page has options to name your project (and solution), choose a disk location, and select a Framework version (if applicable to the template you chose).
Click Create to create the new project.
Step 4
In create a new ASP.NET Web Application window choose MVC template click on create. Visual Studio will generate MVC Web Application project for you.
Step 5
In Visual Studio tools go to NuGet Package Manager and select Manage NuGet Packages for solution.
Install the following package for this application,
- Bootstrap latest version
- Jquery latest version
- Datatables latest version
- Entity framework latest version
Step 6
Right click on Models Folder choose new item “Add” class Employee.
- using System;
- using System.ComponentModel.DataAnnotations;
-
- namespace JQueryDatatableSingleColumnSearchMvc_Demo.Models
- {
- public class Employee
- {
- [Key]
- public int Id { get; set; }
-
- [Required]
- [StringLength(100)]
- public string Name { get; set; }
-
- [Required]
- [StringLength(100)]
- public string Position { get; set; }
-
- [Required]
- [StringLength(100)]
- public string Office { get; set; }
-
- [Required]
- public int Age { get; set; }
-
- [Required]
- [DataType(DataType.Date)]
- public DateTime StartDate { get; set; }
-
- [Required]
- [DataType(DataType.Currency)]
- public decimal Salary { get; set; }
- }
- }
Step 7
Create Data Folder and add class ApplicationDbContext for database communication.
- using JQueryDatatableHideShowColumnsMvc_Demo.Models;
- using System.Data.Entity;
-
- namespace JQueryDatatableHideShowColumnsMvc_Demo.Data
- {
- public class ApplicationDbContext : DbContext
- {
- public ApplicationDbContext() : base("EmployeeDB")
- {
-
- }
-
- public DbSet<Employee> Employees { get; set; }
- }
- }
Step 8
- Enable-migrations
- Add-Migration InitialModel
- Update-database
Step 9
Add bootstrap, jQuery and datatable plugin in _Layout.cshtm
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title</title>
- @Styles.Render("~/Content/css")
- @Scripts.Render("~/bundles/modernizr")
- <link href="~/Content/DataTables/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
- </head>
- <body>
- <div class="container py-4">
- @RenderBody()
- </div>
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/bootstrap")
- <script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
- <script src="~/Scripts/DataTables/dataTables.bootstrap4.min.js"></script>
- @RenderSection("scripts", required: false)
- </body>
- </html>
Step 10
You already have HomeController in Controllers folder if you don’t have it. Add HomeController in Controllers folder and write the following code.
- using JQueryDatatableHideShowColumnsMvc_Demo.Data;
- using System.Linq;
- using System.Web.Mvc;
-
- namespace JQueryDatatableHideShowColumnsMvc_Demo.Controllers
- {
- public class HomeController : Controller
- {
- private readonly ApplicationDbContext db = new ApplicationDbContext();
- public ActionResult Index()
- {
- return View();
- }
-
- public ActionResult GetData()
- {
- var employee = db.Employees.ToList();
- return Json(new { data = employee }, JsonRequestBehavior.AllowGet);
- }
- }
- }
Step 11
In views folder under Home folder in Index.cshtml view Add the following code:
- @{
- ViewBag.Title = "Home";
- }
-
- <h3 class="text-center text-uppercase">List of employees</h3>
-
- <table id="example" class="table table-bordered" style="width:100%;">
- <thead>
- <tr>
- <th>Id</th>
- <th>Name</th>
- <th>Position</th>
- <th>Office</th>
- <th>Age</th>
- <th>Start Date</th>
- <th>Salary</th>
- </tr>
- </thead>
- <tfoot>
- <tr>
- <th>Id</th>
- <th>Name</th>
- <th>Position</th>
- <th>Office</th>
- <th>Age</th>
- <th>Start Date</th>
- <th>Salary</th>
- </tr>
- </tfoot>
- </table>
-
- @section scripts{
- <script type="text/javascript">
- $(document).ready(function () {
- var datatableInstance = $('#example').DataTable({
- "ajax": {
- "url": '/Home/GetData',
- "type": 'GET',
- "dataType": 'json',
- },
- "columns": [
- { 'data': 'Id' },
- { 'data': 'Name' },
- { 'data': 'Position' },
- { 'data': 'Office' },
- { 'data': 'Age' },
- {
- 'data': 'StartDate',
- 'render': function (jsonDate) {
- var date = new Date(parseInt(jsonDate.substr(6)));
- var month = ("0" + (date.getMonth() + 1)).slice(-2);
- return ("0" + date.getDate()).slice(-2) + '-' + month + '-' + date.getFullYear();
- }
- },
- {
- 'data': 'Salary',
- 'render': function (salary) {
- return '$' + salary;
- }
- }
- ]
- });
- $('#example tfoot th').each(function () {
- var title = $('#example thead th').eq($(this).index()).text();
- $(this).html('<input type="text" class="form-control" placeholder="Search ' + title + '" />');
- });
- datatableInstance.columns().every(function () {
- var dataTableColumn = this;
- $(this.footer()).find('input').on('keyup change', function () {
- dataTableColumn.search(this.value).draw();
- });
- });
- });
- </script>
- }
Step 12
Now it’s time to build and run your application >> ctrl+F5