Datatable Dynamic Columns With Server Side

Datatable Dynamic Columns With Server Side

ekbordoekbordo Posts: 12Questions: 8Answers: 0

Hello Guys;

I have a list of list model(List<List<ExampleClass>>). I want to list this model on the datatable. The problem is that i do not know the columns names and how many columns exist. How can i handle this problem?

Any suggestion?

Thank you.

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Do youmean on the client-side (Javascript), or the server-side? I'll assume Javascript for this answer - you need to create the Javascript that defines it dynamically. That can be done in one of two ways:

    1 - Ajax request the table defination from the server which will respond with JSON. You then use that JSON to define the columns.

    2 - Have the server dynamically create the Javascript that defines the DataTable. This would save you an Ajax request, but requires the server to produce valid Javascript, so is parhaps a bit harder.

    I've used both approaches myself in the past, and both can work well.

    Allan

  • ekbordoekbordo Posts: 12Questions: 8Answers: 0

    The below code shows data and columns title. But, if i remove comments, it does not work and it does not go to the url. The commented section is here :

    /*
    "bProcessing": true,
    "bServerSide": true,
    url: "/Seller/Report/ByProductReportServerSideSearchAction",
    */

  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951
    edited February 2023

    it does not go to the url.

    The option is called ajax not url. Since you are using ajax to fetch the data you won't want to define data.

    I would suggest using a different URL to get the columns. You are using the same URL as the Datatables config. This will return all of the table rows which you don't want when using server side processing.

    Also you probably want to move the ajax.data parameters into the Datatables config using ajax.data as a function, like this example.

    You will want something like this:

    $('#example').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
                url: "/Seller/Report/ByProductReportServerSideSearchAction",
                data: function (d) {
                    d.startDate = $('#StartDate').val();
                    d.endDate = $('#EndDaate').val();
                    d.rangeType = $('#RangeType :selected').val();
                },
        columns: columns
    });
    

    Kevin

Sign In or Register to comment.