Jrockhub.DataTablesServerSide.NETCore 1.0.3

dotnet add package Jrockhub.DataTablesServerSide.NETCore --version 1.0.3
NuGet\Install-Package Jrockhub.DataTablesServerSide.NETCore -Version 1.0.3
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Jrockhub.DataTablesServerSide.NETCore" Version="1.0.3" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Jrockhub.DataTablesServerSide.NETCore --version 1.0.3
#r "nuget: Jrockhub.DataTablesServerSide.NETCore, 1.0.3"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Jrockhub.DataTablesServerSide.NETCore as a Cake Addin
#addin nuget:?package=Jrockhub.DataTablesServerSide.NETCore&version=1.0.3

// Install Jrockhub.DataTablesServerSide.NETCore as a Cake Tool
#tool nuget:?package=Jrockhub.DataTablesServerSide.NETCore&version=1.0.3

Jrockhub DataTables Server Side .NET Core

This will help you to Server Side processor for Jquery DataTables with Asp.Net Core as backend. It will provides a quick way to implement dynamic multiple column searching and sorting along with pagination and excel export at the server side. This can be done by decorating your model properties with simple attributes.

Fix

We have facing issue on referencing the tag Helper

NuGet:

Package Manager:

PM> Install-Package Jrockhub.DataTablesServerSide.NETCore -Version 1.0.3

.NET CLI:

> dotnet add package Jrockhub.DataTablesServerSide.NETCore --version 1.0.3

  • [Searchable]
  • [SearchableString]
  • [SearchableDateTime]
  • [SearchableShort]
  • [SearchableInt]
  • [SearchableLong]
  • [SearchableDecimal]
  • [SearchableDouble]
  • [SearchableEnum(typeof(TEnum))]
  • [NestedSearchable]

Sort

  • [Sortable]
  • [Sortable(Default = true)]
  • [NestedSortable]

All the above attributes have the following options,

Mode Option Type Example Description
Search EntityProperty string [Searchable*(EntityProperty = "EntityPropertyName")] To map your view model property with entity property if they have a different name
Nested Search ParentEntityProperty string [NestedSearchable(ParentEntityProperty = "ParentEntityPropertyName")] To map your view model property with entity property if they have a different name
Sort EntityProperty string [Sortable(EntityProperty = "EntityPropertyName")] To map your view model property with entity property if they have a different name
Sort Default bool [Sortable(Default = true)] To indicate your database to do default sort by this property if no sort is specified from client
Nested Sort ParentEntityProperty string [NestedSortable(EntityProperty = "EntityPropertyName")] To map your view model property with entity property if they have a different name

Columns

Name

Column names in HTML Table can be configured using the below attributes

  • [Display(Name = "")]
  • [DisplayName(��)]

HTML Setup

To customize the HTML Column display in <JRH-DataGrid> Tag Helper, use the following attribute

  • [JqueryDataTableColumn]

And here are the options,

Option Type Example Description
Exclude bool [JqueryDataTableColumn(Exclude = true)] To exclude the property of your model from being added in HTML
Order int [JqueryDataTableColumn(Order = N)] To control the order of columns in HTML

Please note: From v.1.0.3 all the simple properties in your models must have [JqueryDataTableColumn] attribute for the <JRH-DataGrid> Tag Helper to work.

Compatibility Chart

The following chart describes the operator compatibility with data types with green as compatible and red as not compatible.

Operator Description string DateTime short int long decimal double enum
co Contains :heavy_check_mark: :x: :x: :x: :x: :x: :x: :heavy_check_mark:
eq Equals ✔️ :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark:
gt GreaterThan :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :x:
gte GreaterThanEqual :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :x:
lt LesserThan :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :x:
lte LesserThanEqual :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :x:

Startup.cs

Asp.Net Core 6.x:

Json.NET has been removed from the ASP.NET Core shared framework.

The default for ASP.NET Core is now System.Text.Json, which is new in .NET Core 6.0. Consider using System.Text.Json when possible. It's high-performance and doesn't require an additional library dependency. I prefer to use Miscrosoft's new System.Text.Json.

With System.Text.Json, setup your ConfigureServices as follows:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews()
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
            });
    services.AddSession();
    services.AddAutoMapper(typeof(Startup));
}

If your using Json.Net, then add a package reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson and then setup your ConfigureServices as follows:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews()
            .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
    services.AddSession();
    services.AddAutoMapper(typeof(Startup));
}

Please note: services.AddSession() is is required only if you're using excel export functionality in Jquery DataTables.

Tag Helpers

Add a JqueryDataTables TagHelper reference to your _ViewImports.cshtml file as shown below

@addTagHelper *, Jrockhub.DataTablesServerSide.NETCore

Table HTML

We have written <jquery-datatables> TagHelper to do the heavy lifting works for you.

<JRH-DataGrid-Localized-Html id="jrockhub_01"
                   class="table table-sm table-dark table-bordered table-hover"
                   model="@Model"
                   thead-class="text-center"
                   enable-searching="true"
                   search-row-th-class="p-0"
                   search-input-class="form-control form-control-sm"
                   search-input-style="width: 100%"
                   search-input-placeholder-prefix="Search">
</JRH-DataGrid-Localized-Html>

Please note: If you prefer HTML Localization then, <jquery-datatables-html> Tag Helper is available with all the above properties.

TagHelpers Attributes

Option Description
id to add id to the html table
class to apply the given css class to the html table
model view model with properties to generate columns for html table
thead-class to apply the given css class to the <thead> in html table
enable-searching true to add search inputs to the <thead> and false to remove search inputs from the <thead>
search-row-th-class to apply the given css class to the search inputs row of the <thead> in the html table
search-input-class to apply the given css class to the search input controls added in each column inside <thead>
search-input-style to apply the given css styles to the search input controls added in each column inside <thead>
search-input-placeholder-prefix to apply your placeholder text as prefix in search input controls in each column inside <thead>
use-property-type-as-input-type to generate HTML5 type input controls based on property type

Initialize DataTable

Add the following code to initialize DataTable. Don't miss to add orderCellsTop : true. This makes sure to add sorting functionality to the first row in the table header. For other properties refer Jquery DataTables official documentation.

Use AdditionalValues to pass extra parameters if required to the server for processing. Configure Column properties and add the required search operator in the name property to perform search based on the operator in the name property. If name property is null or string.Empty, the search default's to Equals search operation.

Please note: Search Operator must be one among the following eq | co | gt | gte | lt | lte based on the above compatibility chart.

AJAX POST Configuration

var table = $('#jrockhub_01').DataTable({
        language: {
            processing: "Loading Data...",
            zeroRecords: "No matching records found"
        },
        processing: true,
        serverSide: true,
        orderCellsTop: true,
        autoWidth: true,
        deferRender: true,
        lengthMenu: [[5, 10, 15, 20, -1], [5, 10, 15, 20, "All"]],
        dom: '<"row"<"col-sm-12 col-md-6"B><"col-sm-12 col-md-6 text-right"l>><"row"<"col-sm-12"tr>><"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
        buttons: [
            {
                text: 'Export to Excel',
                className: 'btn btn-sm btn-dark',
                action: function (e, dt, node, config) {
                    window.location.href = "/Home/GetExcel";
                },
                init: function (api, node, config) {
                    $(node).removeClass('dt-button');
                }
            }
        ],
        ajax: {
            type: "POST",
            url: '/Home/LoadTable/',
            contentType: "application/json; charset=utf-8",
            async: true,
            headers: {
                "XSRF-TOKEN": document.querySelector('[name="__RequestVerificationToken"]').value
            },
            data: function (data) {
                let additionalValues = [];
                additionalValues[0] = "Additional Parameters 1";
                additionalValues[1] = "Additional Parameters 2";
                data.AdditionalValues = additionalValues;

                return JSON.stringify(data);
            }
        },
        columns: [
            {
                data: "Id",
                name: "eq",
                visible: false,
                searchable: false
            },
            {
                data: "Name",
                name: "eq"
            },
            {
                data: "Position",
                name: "co"
            },
            {
                data: "Offices",
                name: "eq"
            },
            {
                data: "NestedLevelOne.Experience",
                name: "eq"
            },
            {
                data: "NestedLevelOne.Extension",
                name: "eq"
            },
            {
                data: "NestedLevelOne.NestedLevelTwos.StartDates",
                render: function (data, type, row) {
                    if (data)
                        return window.moment(data).format("DD/MM/YYYY");
                    else
                        return null;
                },
                name: "gt"
            },
            {
                data: "NestedLevelOne.NestedLevelTwos.Salary",
                name: "lte"
            }
        ]
    });

AJAX GET Configuration

For AJAX GET configuration, simply change the ajax and buttons options as follows,

buttons: [
            {
                text: 'Export to Excel',
                className: 'btn btn-sm btn-dark',
                action: function (e, dt, node, config) {
                    var data = table.ajax.params();
                    var x = JSON.stringify(data, null, 4);
                    window.location.href = "/Home/GetExcel?" + $.param(data);
                },
                init: function (api, node, config) {
                    $(node).removeClass('dt-button');
                }
            }
        ],
ajax: {
            url: '/Home/LoadTable/',
            data: function (data) {
                return $.extend({}, data, {
                    "additionalValues[0]": "Additional Parameters 1",
                    "additionalValues[1]": "Additional Parameters 2"
                });
            }
       }

Add the following script to trigger search only onpress of Enter Key.

table.columns().every(function (index) {
        $('#jrockhub_01 thead tr:last th:eq(' + index + ') input')
            .on('keyup',
                function (e) {
                    if (e.keyCode === 13) {
                        table.column($(this).parent().index() + ':visible').search(this.value).draw();
                    }
                });
    });

Add the following script to trigger search onpress of Tab Key

$('#jrockhub_01 thead tr:last th:eq(' + index + ') input')
    .on('blur',
	    function () {
		    table.column($(this).parent().index() + ':visible').search(this.value).draw();
       });

Model to be passed to DataTable

Decorate the properties based on their data types. For Nested Complex Properties, decorate them with [NestedSearchable]/[NestedSortable]/[NestedIncludeInReport] attributes upto any level.

Root Model:

public class MainClass
{
    [JqueryDataTableColumn(Order = 1)]
    public int Id { get; set; }

    [IncludeInReport(Order = 1)]
    [JqueryDataTableColumn(Order = 2)]
    [SearchableString(EntityProperty = "FirstName,LastName")]
    [Sortable(EntityProperty = "FirstName,LastName", Default = true)]
    public string Name { get => $"{FirstName} {LastName}"; }
    
    [JqueryDataTableColumn(Exclude = true)]
    public string FirstName { get; set; }

    [JqueryDataTableColumn(Exclude = true)]
    public string LastName { get; set; }

    [IncludeInReport(Order = 2)]
    [JqueryDataTableColumn(Order = 3)]
    [SearchableEnum(typeof(Position))]
    [Sortable]
    public string Position { get; set; }

    [Display(Name = "Office")]
    [IncludeInReport(Order = 3)]
    [JqueryDataTableColumn(Order = 4)]
    [SearchableString(EntityProperty = "Office")]
    [Sortable(EntityProperty = "Office")]
    public string Offices { get; set; }

    [NestedIncludeInReport]
    [NestedSearchable]
    [NestedSortable]
    public NestedLevelOne NestedLevelOne { get; set; }
}

Nested Level One Model:

public class NestedLevelOne
{
    [IncludeInReport(Order = 4)]
    [JqueryDataTableColumn(Order = 5)]
    [SearchableShort]
    [Sortable]
    public short? Experience { get; set; }

    [DisplayName("Extn")]
    [IncludeInReport(Order = 5)]
    [JqueryDataTableColumn(Order = 6)]
    [SearchableInt(EntityProperty = "Extn")]
    [Sortable(EntityProperty = "Extn")]
    public int? Extension { get; set; }

    [NestedIncludeInReport]
    [NestedSearchable(ParentEntityProperty = "NestedLevelTwo")]
    [NestedSortable(ParentEntityProperty = "NestedLevelTwo")]
    public NestedLevelTwo NestedLevelTwos { get; set; }
}

Nested Level Two Model:

public class NestedLevelTwo
{
    [DisplayName("Start Date")]
    [IncludeInReport(Order = 6)]
    [JqueryDataTableColumn(Order = 7)]
    [SearchableDateTime(EntityProperty = "StartDate")]
    [Sortable(EntityProperty = "StartDate")]
    public DateTime? StartDates { get; set; }

    [IncludeInReport(Order = 7)]
    [JqueryDataTableColumn(Order = 8)]
    [SearchableLong]
    [Sortable]
    public long? Salary { get; set; }
}

Please note:

  • If view model properties have different name than entity model, then you can still do mapping using (EntityProperty = 'YourEntityPropertyName'). If they are same then you can ignore this.
  • If view model property is a combination of some other properties like Name property in the above root model, then you can specify them in (EntityProperty = 'YourEntityPropertyName,YourSomeOtherEntityPropertyName'). This will make an implicit OR search in database and sort by YourEntityPropertyName and then by YourSomeOtherEntityPropertyName in database. For Example, take the Name property in root model. It has [SearchableString(EntityProperty = "FirstName,LastName")]. This will generate a implicit OR query like entity.Where(x => x.FirstName.ToLower().Contains("Name") || x.LastName.ToLower().Contains("Name")). Similarly, [Sortable(EntityProperty = "FirstName,LastName", Default = true)] will generate query like entity.OrderBy(x => x.FirstName).ThenBy(x => x.LastName) for ascending order and entity.OrderByDescending(x => x.FirstName).ThenByDescending(x => x.LastName) for descending order.

ActionMethod/PageHandler

On DataTable's AJAX Request, JqueryDataTablesParameters will read the DataTable's state and JqueryDataTablesResult<T> will accept IEnumerable<T> response data to be returned back to table as JsonResult.

AJAX POST Configuration

ActionMethod

[HttpPost]
public async Task<IActionResult> LoadTable([FromBody]JqueryDataTablesParameters param)
{
    try
    {
        // `param` is stored in session to be used for excel export. This is required only for AJAX POST.
        // Below session storage line can be removed if you're not using excel export functionality. 
	// If you're using Json.Net, then uncomment below line else remove below line
	// HttpContext.Session.SetString(nameof(JqueryDataTablesParameters), JsonConvert.SerializeObject(param));
	// If you're using new System.Text.Json then use below line
        HttpContext.Session.SetString(nameof(JqueryDataTablesParameters), JsonSerializer.Serialize(param));
        var results = await _fromDatabaseService.GetDataAsync(param);

        return new JsonResult(new JqueryDataTablesResult<MainClass> {
            Draw = param.Draw,
            Data = results.Items,
            RecordsFiltered = results.TotalSize,
            RecordsTotal = results.TotalSize
        });
    } catch(Exception e)
    {
        Console.Write(e.Message);
        return new JsonResult(new { error = "Internal Server Error" });
    }
}

PageHandler

public async Task<IActionResult> OnPostLoadTableAsync([FromBody]JqueryDataTablesParameters param)
{
    try
    {
        // `param` is stored in session to be used for excel export. This is required only for AJAX POST.
        // Below session storage line can be removed if you're not using excel export functionality. 
	// If you're using Json.Net, then uncomment below line else remove below line
	// HttpContext.Session.SetString(nameof(JqueryDataTablesParameters), JsonConvert.SerializeObject(param));
	// If you're using new System.Text.Json then use below line
        HttpContext.Session.SetString(nameof(JqueryDataTablesParameters), JsonSerializer.Serialize(param));
        var results = await _fromDatabaseService.GetDataAsync(param);

        return new JsonResult(new JqueryDataTablesResult<MainClass> {
            Draw = param.Draw,
            Data = results.Items,
            RecordsFiltered = results.TotalSize,
            RecordsTotal = results.TotalSize
        });
    } catch(Exception e)
    {
        Console.Write(e.Message);
        return new JsonResult(new { error = "Internal Server Error" });
    }
}

AJAX GET Configuration

ActionMethod

public async Task<IActionResult> LoadTable([ModelBinder(typeof(JqueryDataTablesBinder))] JqueryDataTablesParameters param)
{
    try
    {
        var results = await _fromDatabaseService.GetDataAsync(param);

        return new JsonResult(new JqueryDataTablesResult<MainClass> {
            Draw = param.Draw,
            Data = results.Items,
            RecordsFiltered = results.TotalSize,
            RecordsTotal = results.TotalSize
        });
    } catch(Exception e)
    {
        Console.Write(e.Message);
        return new JsonResult(new { error = "Internal Server Error" });
    }
}

PageHandler

public async Task<IActionResult> OnGetLoadTableAsync([ModelBinder(typeof(JqueryDataTablesBinder))] JqueryDataTablesParameters param)
{
    try
    {
        var results = await _fromDatabaseService.GetDataAsync(param);

        return new JsonResult(new JqueryDataTablesResult<MainClass> {
            Draw = param.Draw,
            Data = results.Items,
            RecordsFiltered = results.TotalSize,
            RecordsTotal = results.TotalSize
        });
    } catch(Exception e)
    {
        Console.Write(e.Message);
        return new JsonResult(new { error = "Internal Server Error" });
    }
}

Multiple Column Searching and Sorting

Inject Automapper IConfigurationProvider to make use of ProjectTo<T> before returning the data. Inside the Data Access Method, create IQueryable<TEntity> to hold the query. Now, to perform dynamic multiple column searching use Static Search Processor SearchOptionsProcessor<T,TEntity> and call the Apply() function with query and table columns as parameters. Again for dynamic multiple column sorting, use Static Sort Processor SortOptionsProcessor<T,TEntity> and call the Apply() function with query and table as parameters. To implement pagination, make use of Start and Length from table parameter and return the result as JqueryDataTablesPagedResults.

public class DefaultMainClassService:IMainClassService
{
    private readonly JrockhubDbContext _context;
    private readonly IConfigurationProvider _mappingConfiguration;

    public DefaultMainClassService(JrockhubDbContext context,IConfigurationProvider mappingConfiguration)
    {
        _context = context;
        _mappingConfiguration = mappingConfiguration;
    }

    public async Task<JqueryDataTablesPagedResults<MainClass>> GetDataAsync(JqueryDataTablesParameters table)
    {
        MainClass[] items = null;
        IQueryable<MainClassEntity> query = _context.MainClasss
                                               .AsNoTracking()
                                               .Include(x => x.NestedLevelOne)
                                               .ThenInclude(y => y.NestedLevelTwo);
        query = SearchOptionsProcessor<MainClass,MainClassEntity>.Apply(query,table.Columns);
        query = SortOptionsProcessor<MainClass,MainClassEntity>.Apply(query,table);

        var size = await query.CountAsync();

        if (table.Length > 0)
        {
            items = await query
            .Skip((table.Start / table.Length) * table.Length)
            .Take(table.Length)
            .ProjectTo<MainClass>(_mappingConfiguration)
            .ToArrayAsync();
        }
        else
        {
            items = await query
            .ProjectTo<MainClass>(_mappingConfiguration)
            .ToArrayAsync();
        }

        return new JqueryDataTablesPagedResults<MainClass> {
            Items = items,
            TotalSize = size
        };
    }
}

Please note: If you are having DataAccessLogic in a separate project, the create instance of SearchOptionsProcessor and SortOptionsProcessor inside ActionMethod/Handler and pass it as a parameter to Data Access Logic.

Report

Name

Column names in Report can be configured using the below attributes

  • [Display(Name = "")]
  • [DisplayName("")]

Report Setup

To customize the Column display in Report, use the following attribute

  • [IncludeInReport]

And here are the options,

Option Type Example Description
Order int [IncludeInReport(Order = N)] To control the order of columns in Report

Please note: From v.1.0.1 all the simple properties in your models must have [IncludeInReport] attribute for the report export to work.

Excel Export

To exporting the filtered and sorted data as an excel file, add GetExcel action method in your controller as shown below. Return the data as JqueryDataTablesExcelResult<T> by passing filtered/ordered data, excel sheet name and excel file name. JqueryDataTablesExcelResult Action Result that I have added in the Nuget package. This will take care of converting your data as excel file and return it back to browser.

If you want all the results in excel export without pagination, then please write a separate service method to retrive data without using Take() and Skip()

AJAX POST Configuration

Action Method

public async Task<IActionResult> GetExcel()
{
   // Here we will be getting the param that we have stored in the session in server side action method/page handler
   // and deserialize it to get the required data.
   var param = HttpContext.Session.GetString(nameof(JqueryDataTablesParameters));

   // If you're using Json.Net, then uncomment below line else remove below line
   // var results = await _fromDatabaseService.GetDataAsync(JsonConvert.DeserializeObject<JqueryDataTablesParameters>(param));
   // If you're using new System.Text.Json then use below line
   var results = await _fromDatabaseService.GetDataAsync(JsonSerializer.Deserialize<JqueryDataTablesParameters>(param));
   return new JqueryDataTablesExcelResult<MainClass>(results.Items,"Export Sheet Name","Jrockhub_Guid");
}

Page Handler

public async Task<IActionResult> OnGetExcelAsync()
{
  // Here we will be getting the param that we have stored in the session in server side action method/page handler
  // and deserialize it to get the required data.
  var param = HttpContext.Session.GetString(nameof(JqueryDataTablesParameters));

  // If you're using Json.Net, then uncomment below line else remove below line
  // var results = await _fromDatabaseService.GetDataAsync(JsonConvert.DeserializeObject<JqueryDataTablesParameters>(param));
  // If you're using new System.Text.Json then use below line
  var results = await _fromDatabaseService.GetDataAsync(JsonSerializer.Deserialize<JqueryDataTablesParameters>(param));
  return new JqueryDataTablesExcelResult<MainClass>(results.Items,"Export Sheet Name","Jrockhub_Guid");
}

AJAX GET Configuration

Action Method

public async Task<IActionResult> GetExcel([ModelBinder(typeof(JqueryDataTablesBinder))] JqueryDataTablesParameters param)
{
    var results = await _fromDatabaseService.GetDataAsync(param);
    return new JqueryDataTablesExcelResult<MainClass>(results.Items,"Export Sheet Name","Jrockhub_Guid");
}

Page Handler

public async Task<IActionResult> OnGetExcelAsync([ModelBinder(typeof(JqueryDataTablesBinder))] JqueryDataTablesParameters param)
{
    var results = await _fromDatabaseService.GetDataAsync(param);
    return new JqueryDataTablesExcelResult<MainClass>(results.Items,"Export Sheet Name","Jrockhub_Guid");
}

CSV Export

To exporting the filtered and sorted data as an CSV file, add GetCSV action method in your controller as shown below. Return the data as JqueryDataTablesCSVResult<T> by passing filtered/ordered data, excel sheet name and excel file name. JqueryDataTablesCSVResult Action Result that I have added in the Nuget package. This will take care of converting your data as excel file and return it back to browser.

If you want all the results in excel export without pagination, then please write a separate service method to retrive data without using Take() and Skip()

AJAX POST Configuration

Action Method

public async Task<IActionResult> GetCSV()
{
   // Here we will be getting the param that we have stored in the session in server side action method/page handler
   // and deserialize it to get the required data.
   var param = HttpContext.Session.GetString(nameof(JqueryDataTablesParameters));

   // If you're using Json.Net, then uncomment below line else remove below line
   // var results = await _fromDatabaseService.GetDataAsync(JsonConvert.DeserializeObject<JqueryDataTablesParameters>(param));
   // If you're using new System.Text.Json then use below line
   var results = await _fromDatabaseService.GetDataAsync(JsonSerializer.Deserialize<JqueryDataTablesParameters>(param));
   return new JqueryDataTablesCSVResult<MainClass>(results.Items,"Jrockhub_Guid");
}

Page Handler

public async Task<IActionResult> OnGetCSVAsync()
{
  // Here we will be getting the param that we have stored in the session in server side action method/page handler
  // and deserialize it to get the required data.
  var param = HttpContext.Session.GetString(nameof(JqueryDataTablesParameters));

  // If you're using Json.Net, then uncomment below line else remove below line
  // var results = await _fromDatabaseService.GetDataAsync(JsonConvert.DeserializeObject<JqueryDataTablesParameters>(param));
  // If you're using new System.Text.Json then use below line
  var results = await _fromDatabaseService.GetDataAsync(JsonSerializer.Deserialize<JqueryDataTablesParameters>(param));
  return new JqueryDataTablesCSVResult<MainClass>(results.Items,"Jrockhub_Guid");
}

AJAX GET Configuration

Action Method

public async Task<IActionResult> GetCSV([ModelBinder(typeof(JqueryDataTablesBinder))] JqueryDataTablesParameters param)
{
    var results = await _fromDatabaseService.GetDataAsync(param);
    return new JqueryDataTablesCSVResult<MainClass>(results.Items,"Jrockhub_01");
}

Page Handler

public async Task<IActionResult> OnGetCSVAsync([ModelBinder(typeof(JqueryDataTablesBinder))] JqueryDataTablesParameters param)
{
    var results = await _fromDatabaseService.GetDataAsync(param);
    return new JqueryDataTablesCSVResult<MainClass>(results.Items,"Jrockhub_01");
}

Please note: GetReport ActionMethod/Handler name must match the name you define in the excel export action click in your Jquery DataTable Initialization script. From v1.0.0 [IncludeInReport(Order = N)] attribute needs to be present in your model to include the field in your excel report.

Coming Soon

DataTablesServerSide is actively under development and we have plan to hav even more useful features implemented soon, including:

  • Dynamic Select
  • More Helpers

Target Platform

  • .Net Standard 6.0

Tools Used

  • Visual Studio Community 2022

Other Nuget Packages Used

  • Jrockhub.ExportExcel.NETCore (1.0.0) - For Generating Excel/CSV Report
  • Microsoft.AspNetCore.Mvc.Localization (2.2.0) - For HTML Localization in Tag elper
  • Microsoft.AspNetCore.Razor (2.2.0) - For using TagHelper
  • NETStandard.Library (2.0.3) - For standard .NET APIs that are prescribed to be used and supported together
  • Newtonsoft.Json (13.0.1) - For Serialization/Deserialization
  • System.Text.Json (6.0.6) - For Serialization/Deserialization

Author

  • Jrockhub - Software Development.

License

Jrockhub DataTablesServerSide is release under the MIT license. You are free to use, modify and distribute this software, as long as the copyright header is left intact.

Enjoy!

Sponsors

we have happy to help you with our Nuget Package. Please support this project, Please pay us onSponsor via PayPal

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.3 848 10/31/2022
1.0.2 333 10/31/2022
1.0.1 386 10/30/2022
1.0.0 373 10/30/2022

You can easly ues Html Helper with .NETCore Jrockhub Datatable Server Side V1.0.0 with the help of this nuget packages.
If you have any issue to use or upgrade version release then please write us to nuget.support@jrockhub.com