Logo

dev-resources.site

for different kinds of informations.

ASP.NET8 using DataTables.net โ€“ Part2 โ€“ Action buttons

Published at
11/7/2024
Categories
aspnet
datatables
Author
markpelf
Categories
2 categories in total
aspnet
open
datatables
open
Author
8 person written this
markpelf
open
ASP.NET8 using DataTables.net โ€“ Part2 โ€“ Action buttons

A practical guide to using jQuery DataTables.net component in Asp.Net 8 MVC application.

Abstract: A practical guide to building an Asp.Net 8 MVC application that uses jQuery component DataTables.net. This is a continuation of article Part1.

1 ASP.NET8 using jQuery DataTables.net

I was evaluating the jQuery DataTables.net component [1] for usage in ASP.NET8 projects and created several prototype (proof-of-concept) applications that are presented in these articles.

1.1 Articles in this series

Articles in this series are:

  • ASP.NET8 using DataTables.net โ€“ Part1 โ€“ Foundation
  • ASP.NET8 using DataTables.net โ€“ Part2 โ€“ Action buttons
  • ASP.NET8 using DataTables.net โ€“ Part3 โ€“ State saving
  • ASP.NET8 using DataTables.net โ€“ Part4 โ€“ Multilingual
  • ASP.NET8 using DataTables.net โ€“ Part5 โ€“ Passing additional parameters in AJAX
  • ASP.NET8 using DataTables.net โ€“ Part6 โ€“ Returning additional parameters in AJAX
  • ASP.NET8 using DataTables.net โ€“ Part7 โ€“ Buttons regular
  • ASP.NET8 using DataTables.net โ€“ Part8 โ€“ Select rows
  • ASP.NET8 using DataTables.net โ€“ Part9 โ€“ Advanced Filters

2 Final result

The goal of this article is to create a proof-of-concept application that demos action buttons with actions attached to them. Action buttons invoke action with the particular row ID passed to the action. Let us present the result of this article.

The topic of this article is how to create buttons inside DataTables component and how to pass row ID to the action.

3 Client-side DataTables.net component

Here I will just show what the ASP.NET view using DataTables component looks like.

<!-- Employees.cshtml -->
<partial name="_LoadingDatatablesJsAndCss" />

@{
    <div class="text-center">
        <h3 class="display-4">Employees table</h3>
    </div>

    <!-- Here is our table HTML element defined. JavaScript library Datatables
    will do all the magic to turn it into interactive component -->
    <table id="EmployeesTable01" class="table table-striped table-bordered ">
    </table>
}


<script>
    // Datatables script initialization=========================================
    // we used defer attribute on jQuery so it might not be available at this point
    // so we go for vanilla JS event

    document.addEventListener("DOMContentLoaded", InitializeDatatable);

    function InitializeDatatable() {
        $("#EmployeesTable01").dataTable({
            //processing-Feature control the processing indicator.
            processing: true,
            //paging-Enable or disable table pagination.
            paging: true,
            //info-Feature control table information display field
            info: true,
            //ordering-Feature control ordering (sorting) abilities in DataTables.
            ordering: true,
            //searching-Feature control search (filtering) abilities
            searching: true,
            //search.return-Enable / disable DataTables' search on return.
            search: {
                return: true
            },
            //autoWidth-Feature control DataTables' smart column width handling.
            autoWidth: true,
            //lengthMenu-Change the options in the page length select list.
            lengthMenu: [10, 15, 25, 50, 100],
            //pageLength-Change the initial page length (number of rows per page)
            pageLength: 15,

            //order-Initial order (sort) to apply to the table.
            order: [[1, 'asc']],

            //serverSide-Feature control DataTables' server-side processing mode.
            serverSide: true,

            //Load data for the table's content from an Ajax source.
            ajax: {
                "url": "@Url.Action("EmployeesDT", "Home")",
                "type": "POST",
                "datatype": "json"
            },

            //Set column specific initialisation properties
            columns: [
                //name-Set a descriptive name for a column
                //data-Set the data source for the column from the rows data object / array
                //title-Set the column title
                //orderable-Enable or disable ordering on this column
                //searchable-Enable or disable search on the data in this column
                //type-Set the column type - used for filtering and sorting string processing
                //visible-Enable or disable the display of this column.
                //width-Column width assignment.
                //render-Render (process) the data for use in the table.
                //className-Class to assign to each cell in the column.

                {   //0
                    name: 'id',
                    data: 'id',
                    title: "Employee Id",
                    orderable: true,
                    searchable: false,
                    type: 'num',
                    visible: true
                },
                {
                    //1
                    name: 'givenName',
                    data: "givenName",
                    title: "Given Name",
                    orderable: true,
                    searchable: true,
                    type: 'string',
                    visible: true
                },
                {
                    //2
                    name: 'familyName',
                    data: "familyName",
                    title: "Family Name",
                    orderable: true,
                    searchable: true,
                    type: 'string',
                    visible: true
                },
                {
                    //3
                    name: 'town',
                    data: "town",
                    title: "Town",
                    orderable: true,
                    searchable: true,
                    type: 'string',
                    visible: true
                },
                {
                    //4
                    name: 'country',
                    data: "country",
                    title: "Country",
                    orderable: true,
                    searchable: true,
                    type: 'string',
                    visible: true,
                    width: "150px",
                    className: 'text-center '
                },
                {
                    //5
                    name: 'email',
                    data: "email",
                    title: "Email",
                    orderable: true,
                    searchable: true,
                    type: 'string',
                    visible: true
                },
                {
                    //6
                    name: 'phoneNo',
                    data: "phoneNo",
                    title: "Phone Number",
                    orderable: false,
                    searchable: true,
                    type: 'string',
                    visible: true
                },
                {
                    //7
                    name: 'actions',
                    data: "actions",
                    title: "Actions",
                    orderable: false,
                    searchable: false,
                    type: 'string',
                    visible: true,
                    render: renderActions
                },
                {
                    //8
                    name: 'urlForEdit',
                    data: "urlForEdit",
                    title: "urlForEdit",
                    orderable: false,
                    searchable: false,
                    type: 'string',
                    visible: false
                }
            ]
        });

        function renderActions(data, type, row, meta) {
            //for Edit button we get Url from the table data
            let html1 =
                '<a class="btn btn-info" href="' +
                row.urlForEdit + '">Edit</a>';

            //for Info button we create Url in JavaScript
            let infoUrl = "@Url.Action("EmployeeInfo", "Home")" +
                "?EmployeeId=" + row.id;
            let html2 =
                '<a class="btn btn-info"  style="margin-left: 10px" href="' +
                infoUrl + '">Info</a>';

            return html1 + html2;
        }
    }
</script>


Enter fullscreen mode Exit fullscreen mode

Note the โ€œrenderโ€ property in โ€œactionsโ€ column. That is where buttons rendering is invoked.

We are showing 2 ways to create an action URL:

  1. Creation of URL with ID on the server side (Edit button)
  2. Creation of URL with ID on the client side (info button)

Sometimes it can be more convenient to create complicated URLs on the server side, with C# tools, where more data is available. Then we use a trick, to pass it to the client-side component as a table column โ€œurlForEditโ€, which is not visible. That is shown for the Edit button.

Also, of course, you can create URLs on the client side, if you like JavaScript. That is shown for the Info button.

4 ASP.NET back-end processing

We can look now at the server side, where processing is done. New is only how we create urlForEdit and pass it to the client side.

//HomeController.cs

 //this is target of AJAX call and provides data for
 //the table, based on selected input parameters
 public IActionResult EmployeesDT(DataTables.AspNet.Core.IDataTablesRequest request)
 {
     // There is dependency in this method on names of fields
     // and implied mapping. I see it almost impossible to avoid.
     // At least, in this method, we avoided dependency on the order
     // of table fields, in case order needs to be changed
     //Here are our mapped table columns:
     //Column0 id -> Employee.Id
     //Column1 givenName -> Employee.FirstName
     //Column2 familyName -> Employee.LastName
     //Column3 town -> Employee.City
     //Column4 country -> Employee.Country
     //Column5 email -> Employee.Email
     //Column6 phoneNo -> Employee.Phone
     //Column7 actions 
     //Column8 urlForEdit 

     try
     {
         IQueryable<Employee> employees = MockDatabase.MockDatabase.Instance.EmployeesTable.AsQueryable();

         int totalRecordsCount = employees.Count();

         var iQueryableOfAnonymous = employees.Select(p => new
         {
             id = p.Id,
             givenName = p.FirstName,
             familyName = p.LastName,
             town = p.City,
             country = p.Country,
             email = p.Email,
             phoneNo = p.Phone,
         });

         iQueryableOfAnonymous = FilterRowsPerRequestParameters(iQueryableOfAnonymous, request);

         int filteredRecordsCount = iQueryableOfAnonymous.Count();

         iQueryableOfAnonymous = SortRowsPerRequestParamters(iQueryableOfAnonymous, request);

         iQueryableOfAnonymous = iQueryableOfAnonymous.Skip(request.Start).Take(request.Length);

         var dataPage = iQueryableOfAnonymous.ToList();
         var dataPage2 = dataPage.Select(p => new
         {
             p.id,
             p.givenName,
             p.familyName ,
             p.town ,
             p.country ,
             p.email ,
             p.phoneNo ,
             actions = System.String.Empty,
             urlForEdit = Url.Action("EmployeeEdit", "Home", new { EmployeeId = p.id }),
         }).ToList();

         var response = DataTablesResponse.Create(request, totalRecordsCount, filteredRecordsCount, dataPage2);

         return new DataTablesJsonResult(response, false);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
         var response = DataTablesResponse.Create(request, "Error processing AJAX call on server side");
         return new DataTablesJsonResult(response, false);
     }
 }
Enter fullscreen mode Exit fullscreen mode

5 Conclusion

The full example code project can be downloaded at GitHub [99].

6 References

[1] https://datatables.net/

[99] https://github.com/MarkPelf/ASPNET8UsingDataTablesNet

aspnet Article's
30 articles in total
Favicon
The Future of ASP.NET: What to Expect
Favicon
DevExpress - Enhancing ASP.NET Web Forms with the ASPxGridView Control
Favicon
Advanced Search in .NET with Elasticsearch(Full Video)
Favicon
Introducing Brick SaaS Starter Kit - Launch SaaS Products Faster
Favicon
Using server sent events in ASP.NET
Favicon
Important Links
Favicon
Serverless OAuth2/OIDC server with OpenIddict 6 and RDS Aurora v2
Favicon
Learning in Reverse: How I Would Learn ASP. Net Core and Entity Framework If I Could Go Back In Time
Favicon
Dependency injection validation error in ASP.NET Core projects
Favicon
Agrupamiento de datos de una lista usando LINQ en C#
Favicon
Asp .Net: Create a Simple 'Web User Control'
Favicon
[ASP.NET] ๅฆ‚ไฝ•ๅฐŽๅ‘ๅˆฐ้Œฏ่ชค้ ้ข
Favicon
DevExpress - Simplifying Server-to-Client Data Transfer with ASPxCallback JSProperties
Favicon
Asp.net
Favicon
[ASP.NET] ่จญ็ฝฎ่ˆ‡ๅ–ๅพ— Web.config ่‡ชๅฎš็พฉ่ณ‡ๆ–™
Favicon
How to Hire Dedicated .NET Developers
Favicon
Permission-Based Authorization in ASP.NET Core: A Step-by-Step Guide
Favicon
Permission-Based Authorization in ASP.NET Core: A Step-by-Step Guide
Favicon
Dependency Container and Services Lifetimes (ะะฐ ั€ัƒััะบะพะผ)
Favicon
Containerize ASP.NET Core API, Entity Framework with SQL Server, Let's Encrypt, Docker, and Nginx (Part 1)
Favicon
differences of Transient and scoped in ASP NET
Favicon
ASP.NET8 using DataTables.net โ€“ Part6 โ€“ Returning additional parameters in AJAX
Favicon
ASP.NET8 using DataTables.net โ€“ Part4 โ€“ Multilingual
Favicon
ASP.NET8 using DataTables.net โ€“ Part8 โ€“ Select rows
Favicon
ASP.NET8 using DataTables.net โ€“ Part3 โ€“ State saving
Favicon
ASP.NET8 using DataTables.net โ€“ Part7 โ€“ Buttons regular
Favicon
ASP.NET8 using DataTables.net โ€“ Part5 โ€“ Passing additional parameters in AJAX
Favicon
ASP.NET8 using DataTables.net โ€“ Part9 โ€“ Advanced Filters
Favicon
ASP.NET8 using DataTables.net โ€“ Part2 โ€“ Action buttons
Favicon
ASP.NET 8 โ€“ Multilingual Application with single Resx file โ€“ Part 3 โ€“ Forms Validation Strings

Featured ones: