DatatableJS is a helper to create a grid with Jquery Datatable and provides an extension to retrieve data generically from the Entity Framework context. It is possible to use many datatable.js features with HTML helper. It gives server-side or client-side options. There's more: Wiki Documentation
Install DatatableJS for .Net Core, .Net 5, .Net 6 and use tag helpers.
PM> Install-Package DatatableJS
@(Html.JS().Datatable<Person>()
.Name("PersonGrid")
.Columns(col =>
{
col.Field(a => a.Id).Visible(false);
col.Field(a => a.Name).Title("First Name").Class("text-danger");
col.Field(a => a.Age).Title("Age").Searchable(false);
col.Field(a => a.BirthDate).Title("Birth Date").Format("DD-MMM-Y");
col.Command(a => a.Id, "onClick", text: "Click").Title("");
})
.Filters(filter =>
{
filter.Add(a => a.Id).GreaterThanOrEqual(1);
})
.URL(Url.Action("GetDataResult"), "POST")
.ServerSide(true)
.Render()
)
Or, use tag helper:
<js-datatable name="PersonGrid">
<columns>
<column field="Id" visible="false" />
<column field="Name" width="50" title="Full Name" />
<column field="Age" />
<command-item field="Id" on-click="onClick" btn-class="btn btn-info" text="Edit" icon-class="fa fa-edit"/>
<commands field="Id" text="Actions" items='new [] { new Command("Update", "onClick"), new Command("Delete", "onClick") }'/>
</columns>
<data-source url="@Url.Action("GetDataResult")" method="POST" server-side="true" data="addParam"/>
<language url="//cdn.datatables.net/plug-ins/1.10.22/i18n/Turkish.json"/>
<filters>
<add field="Id" value="1" operand="GreaterThanOrEqual"/>
</filters>
<captions top="top caption here" bottom="bottom caption here"/>
<render />
</js-datatable>
To use on .Net Frameworks (4.5 ... 4.8) Install DatatableJS.Net from the package manager console:
PM> Install-Package DatatableJS.Net
Then add datatables.net Javascript and CSS files or links to your project.
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
Set the URL to retrieve data from any action with GET or POST method:
.URL(Url.Action("GetAll", "Person"), "POST")
If property names are pascal case like "FirstName" and JSON naming policy is camel case like "firstName", enable it.
.URL(Url.Action("GetDataResult"), "POST", camelCase: true)
Use DataRequest
object to bind parameters of request. With .ToDataResult(request);
extension method, if there is entity framework, execute IQueryable list server side from context. Otherwise manipulate data manually and return DataResult<T>
object including data.
Install DatatableJS.Data from the package manager console:
PM> Install-Package DatatableJS.Data
using DatatableJS.Data;
public JsonResult GetAll(DataRequest request)
{
DataResult<Person> result = ctx.People.ToDataResult(request);
return Json(result);
}
Enable server-side processing mode. By default DataTables operates in client-side processing mode. Reference:
.ServerSide(true)
Pass additional parameters with .Data("addParam")
method and add script function to view.
function addParam() {
return { Param1: "test1", Param2: true, Param3: 5 };
}
Get additional parameters with names.
public JsonResult GetAll(DataRequest request, string Param1, bool Param2, int Param3)
{
//
}
Or get parameters with object reference named "data".
public JsonResult GetAll(DataRequest request, AddData data)
{
//
}
Add additional filters before render datatable object. These filters are included in .ToDataResult(request)
method with request while server side executing.
.Filters(filter =>
{
filter.Add(a => a.BirthDate).LessThanOrEqual(DateTime.Now);
filter.Add(a => a.Age).NotEqual(25);
})
Using this method you can define which column(s) the order is performed upon, and the ordering direction. Reference
.Orders(order => {
order.Add(p => p.Name, OrderBy.Descending);
order.Add(p => p.Age, OrderBy.Ascending);
})
This method allows you to readily specify the entries in the length drop down select list that DataTables shows . Reference
.LengthMenu(new int[] {5,10,15})
Set hasAll paramter true to show All option in select.
.LengthMenu(new int[] {5,10,15}, true)
Set allText paramter to change name of option All.
.LengthMenu(new int[] {5,10,15}, true, "All Pages")
Number of rows to display on a single page when using pagination. Reference
.PageLength(15)
Calling datatable on client-side is possible with name:
.Name("GridName")
Default name is "DataGrid". If there are multiple grid in single page, different names should be given. Call grid if you need like this:
$(document).ready(function() {
var table = $('#DataGrid').DataTable();
} );
This option allows the search abilities of DataTables to be enabled or disabled. Default is "true". Reference:
.Searching(false)
Enable or disable ordering of columns - it is as simple as that! DataTables, by default, allows end users to click on the header cell for each column, ordering the table by the data in that column. Default is "true". Reference:
.Ordering(false)
DataTables can split the rows in tables into individual pages, which is an efficient method of showing a large number of records in a small space. The end user is provided with controls to request the display of different data as the navigate through the data. Default is "true". Reference:
.Paging(false)
Select adds item selection capabilities to a DataTable. Items can be rows, columns or cells, which can be selected independently, or together. Reference:
.Selecting(true)
.Selecting(true, SelectItems.Checkbox)
.Selecting(true, SelectItems.Cell, SelectStyle.Single)
Enable or disable the display of a 'processing' indicator when the table is being processed. Default is true. Reference:
.Processing(false)
Enable horizontal scrolling. When a table is too wide to fit into a certain layout, or you have a large number of columns in the table, you can enable horizontal (x) scrolling to show the table in a viewport, which can be scrolled. Reference:
.ScrollX(true)
Default table css class is "display nowrap dataTable dtr-inline collapsed"
. It can be replaced with other table class like bootstrap "table table-striped".
.Class("table table-striped")
Adding some text on table header or footer with Captions method that:
.Captions("Top caption text...", "Bottom caption text...")
FixedColumns provides the option to freeze one or more columns to the left or right of a horizontally scrolling DataTable. Reference:
.FixedColumns(leftColumns: 1, rightColumns: 3)
With this feature, data is be searchable column by column if column searchable is not false.
.ColumnSearching(true)
To give class for these inputs:
.ColumnSearching(true, "form-control")
To change the position of the search boxes (default is Footer):
.ColumnSearching(true, SearchPosition.Header)
.ColumnSearching(true, "form-control", SearchPosition.Header)
Set column header. Default is property name.
.Title("Person Name");
Or use DisplayAttribute
for properties.
[Display(Name = "Person Name")]
public string Name { get; set; }
Customize datetime format with Moment.js expression.
.Format("DD-MMM-Y");
Or use DisplayFormatAttribute
for properties.
[DisplayFormat(DataFormatString = "DD-MMM-Y")]
public DateTime? BirthDate { get; set; }
Manipulate and change display of column according to data.
.Template("(data === true) ? '<span class=\"glyphicon glyphicon-ok\"></span>' : '<span class=\"glyphicon glyphicon-remove\"></span>'");
Set column visible or hidden, default is true
.
.Visible(false);
Set column searchable or not, default is true
.
.Searchable(false);
Set column orderable or not, default is true
.
.Orderable(false);
Set column width percentage.
.Width(50);
Set css class of column.
.Class("text-danger");
Set default value for null data.
.DefaultContent("No Data");
Add column commands to table in a variety of ways.
cols.Command(a => a.Name, "onClick").Title("Link");
cols.Command(a => a.Name, "onClick", "Click").Title("Link");
cols.Command(a => a.Id, "onClick", "Click", "glyphicon glyphicon-edit").Title("Edit");
cols.Command(a => a.Id, "onClick", "Click", "glyphicon glyphicon-edit", "btn btn-danger btn-xs").Title("Edit");
function onClick(e) {
alert(e);
}
Add button groups as a commands.
cols.Commands(a => a.Id, new[] { new Command("Update", "onUpdate"), new Command("Delete", "onDelete") }, "Reports").Title("Actions");
cols.Commands(a => a.Id, new[] { new Command("Excel", "onDelete"), new Command("Pdf", "onUpdate") }, "Reports", "", "", "glyphicon glyphicon-export").Title("Export");
Default language is English. You can change with other languages or custumize it. Set json url parameter to Language method for other languages from CDN.
.Language("https://cdn.datatables.net/plug-ins/1.10.20/i18n/Turkish.json")
Or add json file local and customize it. Reference:
.Language(Url.Content("/Scripts/Turkish.json"))
Json example is below:
{
"sEmptyTable": "No data available in table",
"sInfo": "Showing _START_ to _END_ of _TOTAL_ entries",
"sInfoEmpty": "Showing 0 to 0 of 0 entries",
"sInfoFiltered": "(filtered from _MAX_ total entries)",
"sInfoPostFix": "",
"sInfoThousands": ",",
"sLengthMenu": "Show _MENU_ entries",
"sLoadingRecords": "Loading...",
"sProcessing": "Processing...",
"sSearch": "Search:",
"sZeroRecords": "No matching records found",
"oPaginate": {
"sFirst": "First",
"sLast": "Last",
"sNext": "Next",
"sPrevious": "Previous"
},
"oAria": {
"sSortAscending": ": activate to sort column ascending",
"sSortDescending": ": activate to sort column descending"
}
}
Or, you can just change what you want with builder;
.Language(lang => lang.EmptyTable("No Data").Search("Search by: "))
Jquery datatable supports many callback functionalities:
stateSaveParams: State save - data manipulation callback Reference:
You can easily define them with helper:
.Callbacks(x => x.CreatedRow("createdRow"))
function createdRow(row, data, dataIndex, cells){
console.log(dataIndex + " " + data.Name);
}
Or multiple callback functions:
.Callbacks(x => x.CreatedRow("createdRow").InitComplete("initComplete"))
ColReorder adds the ability for the end user to be able to reorder columns in a DataTable through a click-and-drag operation. This can be useful when presenting data in a table, letting the user move columns that they wish to compare next to each other for easier comparison.
.ColReorder(true)
Or, configure it; Reference:
.ColReorder(x => x.Enable(false))
.ColReorder(x => x.FixedColumnsLeft(1))
.ColReorder(x => x.FixedColumnsRight(1))
.ColReorder(x => x.Order(5,4,3,2,1,0))
.ColReorder(x => x.RealTime(false))