ASP.NET does not provide sortable, searchable tables. jQuery DataTables is a popular way to display user-friendly data in an ASP.NET Core MVC web application.
Set up the environment
- Add the System.Linq.Dynamic.Core NuGet package to the web application
- Add the JsonOptions to the Startup.cs file
using Newtonsoft.Json.Serialization;
- Add the AddJsonOptions to the services.AddMvc() section in the ConfigureServices() method of the Startup.cs file
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
Add the jQuery DataTables grid to the view
- Add the script and css references to the bottom of the view
@section Scripts { <!-- For the DataTables grid --> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css"> <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script> <!-- Page-specific script --> <script src="~/js/MY-CONTROLLER_MY-PAGE.js" asp-append-version="true"></script> }
- Add to the page-specific MY-CONTROLLER_MY-PAGE.js file to the wwwroot\js directory
$(document).ready(function () { // Set up the DataTable grid $('#serverTable').DataTable(); });
- Create a table with the same id referenced in the script
@if (null != Model.ServerList) { <table id="serverTable" class="table table-striped table-bordered dt-responsive nowrap" width="100%"> <thead> <tr> <th></th> <th>Name</th> ... </tr> </thead> <tbody> @foreach (ServerInstance instance in Model.ServerList) { <tr> <td><input type="checkbox" asp-for="@instance.Selected" /></td> <td>@instance.NameTag</td> ... </tr> } </tbody> </table> }
Sorry for – maybe stupid – question but can you be more explicit with :
Model.ServerList from : @if (null != Model.ServerList) expresion
and
ServerInstance instance in Model.ServerList from : @foreach (ServerInstance instance in Model.ServerList)
I am beginner in .net core mvc and I am trying to understand !