Featured
JQuery Datatable in ASP.NET Core - Server-Side Processing
Last modified: June 18, 2021Since there are no built-in Grids in ASP.NET Core MVC, we are going to use one of the most popular DataTable Grid jQuery libraries. We are going to use as server-side.
Step 1
Create an ASP.NET Core MVC application.
Step 2
Right-click the project name and click "Manage Nuget Packages" and search for Microsoft.EntityFrameworkCore NuGet package. Install it, it is ORM (Object-relational mapping) to talk to the database.
We are going to use the In-Memory database for demo purposes, hence we also need to install Microsoft.EntityFrameworkCore.InMemory NuGet library.
For server-side processing, we also need System.Linq.Dynamic.Core Nuget library.
Step 3
We are going to use CDN links to our project.
<link href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
In Home -> Index View, we first create html table containing name, start and end fields and give it an id of "holidayDatatable".
<table id="holidayDatatable" class="table table-striped" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Start Date</th>
<th>End Date</th>
</tr>
</thead>
</table>
To use html table as DataTable Grid, we need to do $("#holidayDatatable").DataTable({
.
@section Scripts {
<link href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#holidayDatatable").DataTable({
"processing": true, //show processing message
"serverSide": true, //is server side
"filter": true, //allow filter
"ajax": {
"url": "/Holiday/GetHoliday", //endpoint to get data from a controller
"type": "POST",
"datatype": "json"
},
"columns": [ // columns to populate
{ "data": "name", "name": "Name", "autoWidth": true },
{ "data": "start", "name": "Start", "autoWidth": true },
{ "data": "end", "name": "End", "autoWidth": true },
]
});
});
</script>
}
Step 4
Create a Holiday.cs class file in the Model folder.
public class Holiday
{
public string Name { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
}
Step 5
Create a Data folder in the root level of your application and then create a DemoContext class file in it. There we set up the ORM (Entity Framework Core) setting.
public class DemoContext : DbContext
{
public DemoContext(DbContextOptions<DemoContext> options) : base(options)
{
}
public DbSet<Holiday> Holiday { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
}
Step 6
Create an Interfaces folder in the root level of the application, and then create IHolidayService interface in it. An interface is similar to a class except it is purely represents a contract between an object and user. We do not put the implementation of a method in the interface file, just the signature.
public interface IHolidayService
{
public IEnumerable<Holiday> GetAll();
}
Step 7
Create a Services folder in the root level of your application and then create a HolidayService class file in it. We inherit IHolidayService interface to HolidayService class. We put some dummy records so that we can test jQuery DataTable.
It is important we return the list as IQueryable so that we can sort by records in Jquery Grid.
public class HolidayService : IHolidayService
{
public IQueryable<Holiday> GetAll()
{
return new List<Holiday>
{
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
new Holiday{Start = DateTime.Now, End = DateTime.Now, Name="Christmas"},
}.AsQueryable();
}
}
Step 8
Create a HolidayController controller file with the template MVC Controller - Empty template. We inject IHolidayService as dependency injection (DI) in the constructor.
[HttpPost]
public IActionResult GetHoliday()
{
try
{
var draw = HttpContext.Request.Form["draw"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault(); //start row
var length = Request.Form["length"].FirstOrDefault(); //pagination length, e.g. 10 item in a page
var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault(); //sort the column name
var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault(); //sort order (asc, desc)
var searchValue = Request.Form["search[value]"].FirstOrDefault(); //get value from search box
int pageSize = length != null ? Convert.ToInt32(length) : 0; //page size 10,20,30
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
var holidaydata = _holidayService.GetAll(); // getting all holiday data
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDirection)))
{
holidaydata = holidaydata.OrderBy(sortColumn + " " + sortColumnDirection);
}
if (!string.IsNullOrEmpty(searchValue))
{
holidaydata = holidaydata.Where(m => m.Name.Contains(searchValue));
}
recordsTotal = holidaydata.Count(); //total number of rows counts
var data = holidaydata.Skip(skip).Take(pageSize).ToList();//Paging
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data });//Returning Json Data
}
catch (Exception)
{
throw;
}
}
Step 9
We also need to add few lines in the startup.cs in ConfigureServices method for FileService DI. Without it, the application will not work.
We add the dbContext (i.e. DemoContext) to use in memory database. and we need to register FileService so that we can use it as DI(dependency injection).
services.AddDbContext<DemoContext>(c =>
c.UseInMemoryDatabase("demo"));
services.AddScoped<IHolidayService, HolidayService>();
Complete source code can be found here