Skip to content

Instantly share code, notes, and snippets.

@hanssens
Created August 12, 2015 12:55
Show Gist options
  • Save hanssens/4960c7203647990b984d to your computer and use it in GitHub Desktop.
Save hanssens/4960c7203647990b984d to your computer and use it in GitHub Desktop.
DataTables server-side pageable, sorteable and filterable grid
public JsonResult Products(IDataTablesRequest request)
{
// Nothing important here. Just creates some mock data.
var data = ProductFactory.Create();
// Global filtering.
// Filter is being manually applied due to in-memmory (IEnumerable) data.
// If you want something rather easier, check IEnumerableExtensions Sample.
var filteredData = data.Where(_item => _item.Name.Contains(request.Search.Value));
// Paging filtered data.
// Paging is rather manual due to in-memmory (IEnumerable) data.
var dataPage = filteredData.Skip(request.Start).Take(request.Length);
// Response creation. To create your response you need to reference your request, to avoid
// request/response tampering and to ensure response will be correctly created.
var response = DataTablesResponse.Create(request, data.Count(), filteredData.Count(), dataPage);
// Easier way is to return a new 'DataTablesJsonResult', which will automatically convert your
// response to a json-compatible content, so DataTables can read it when received.
return new DataTablesJsonResult(response, JsonRequestBehavior.AllowGet);
}
<div class="row">
<table id="grid"></table>
</div>
@section scripts {
<!-- See for CDN includes: https://cdnjs.com/libraries/datatables -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.7/css/jquery.dataTables.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.7/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script>
$(function () {
$('#grid').dataTable({
serverSide: true,
ajax: "/data/products",
columns: [
{
name: 'id',
data: 'id',
title: "Id",
sortable: false,
searchable: false
},
{
name: 'name',
data: "name",
title: "Name",
sortable: false,
searchable: false
}
]
});
});
</script>
}
@hanssens
Copy link
Author

Instructions are quite easy:

  1. Install-Package Newtonsoft.Json (v7.0.1+)

  2. Install-Package DataTables.AspNet.Mvc5 -Pre

  3. Add the following section to your Application_Start / Global.asax:

    DataTables.AspNet.Mvc5.Configuration.Register();

Also, please note the CDN dependencies in the html.

@dtaalbers
Copy link

I believe DataTables.AspNet.Mvc5.Configuration.Register(); has changed to DataTables.AspNet.Mvc5.Configuration.RegisterDataTables();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment