Translate

Home > 2019

2019

Angular DataTables Server side pagination & Sorting

Friday, November 8, 2019 Category : , 10


Installation : https://l-lin.github.io/angular-datatables/#/getting-started

Add a table to angular view


<table datatable [dtOptions]="dtOptions" style="width: 99.5% !important;" class="table table-responsive-sm table-bordered table-striped table-sm">
                                                <thead>
                                                    <tr>
                                                    <th>Client ID</th>
                                                    <th>Client Name</th>
                                                    <th>Client Phone</th>
                                                    <th>Join Date</th>
                                                    <th>Email</th>
                                                    <th>Is Active</th>
                                                    <th>Operation</th>
                                                    </tr>
                                                </thead>
                                                <tbody *ngIf="modelList && modelList?.length != 0">
                                                    <tr *ngFor="let m of modelList">
                                                    <td>{{ m.ClientID }}</td>
                                                    <td>{{ m.ClientName }}</td>
                                                    <td>{{ m.ClientPhone }}</td>
                                                    <td>{{ m.JoinDate | date : "MMM d, y" }}</td>
                                                    <td>{{ m.Email}}</td>
                                                    <td>
                                                            <div class="btn-group project-list-ad" *ngIf="m.IsActive">
                                                                    <button class="btn btn-white btn-xs">Active</button>
                                                            </div>

                                                            <div class="btn-group project-list-ad-rd" *ngIf="!m.IsActive">
                                                                    <button class="btn btn-white btn-xs">Unactive</button>
                                                            </div>
                                                    </td>
                                                    <td>
                                                        <button class="btn btn-pill btn-dark" type="button" (click)='editbuttonClick(m.ClientID)'>
                                                        <i class="fa fa-file-o fa-sm mt-1"></i>&nbsp;Edit
                                                        </button>
                                                    </td>
                                                    </tr>
                                                </tbody>
                                                <tbody *ngIf="!modelList || modelList?.length == 0">
                                                    <tr>
                                                    <td colspan="3" class="no-data-available">No data!</td>
                                                    </tr>
                                                <tbody>
                                                </table>

Type ScriptCode

dtOptions: DataTables.Settings = {};
public modelList: ClientList[]; // your model for store dataset
 

    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 10,
      serverSide: true,
      processing: true,
      ajax: (dataTablesParameters: anycallback=> {
        that._http
          .post<DataTablesResponse>(
            //'https://angular-datatables-demo-server.herokuapp.com/',
            this.env.apiUrl + 'api/setup/ClientList_SelectAll_Grid',
            dataTablesParameters, {}
          ).subscribe(resp => {
            //console.log(dataTablesParameters);
            that.modelList = resp.data;


            callback({
              recordsTotal: resp.recordsTotal,
              recordsFiltered: resp.recordsFiltered,
              data: []
            });
          });
      },
      columns: [{ data: 'ClientID' }, { data: 'ClientName' }, { data: 'ClientPhone' }, { data: 'JoinDate' }, { data: 'Email' }, { data: 'IsActive' }, { defaultContent: ''orderable: false }]
    };

export class DataTablesResponse {
    data: any[];
    draw: number;
    recordsFiltered: number;
    recordsTotal: number;
    error :string;
  }
 

C# Server Side Code

 public class DataTablesRootObject
    {
        public int draw { getset; }
        public List<Columncolumns { getset; }
        public List<Orderorder { getset; }
        public int start { getset; }
        public int length { getset; }
        public Search search { getset; }
    }

    public class Search
    {
        public string value { getset; }
        public string product_segment { getset; }
        public string branchid { getset; }
        public string username { getset; }
        public string vendorno { getset; }

        public string fromdate { getset; }
        public string todate { getset; }

        public bool regex { getset; }
    }

    public class Column
    {
        public string data { getset; }
        public string name { getset; }
        public bool searchable { getset; }
        public bool orderable { getset; }
        public Search search { getset; }
    }

    public class Order
    {
        public int column { getset; }
        public string dir { getset; }
    }

public class DataTablesResponse
    {
        public object data { getset; }
        public int draw { getset; }
        public int recordsFiltered { getset; }
        public int recordsTotal { getset; }
        public string error { getset; }
    }

public DataTablesResponse ClientList_SelectAll_Grid([FromBodyDataTablesRootObject dataTablesRootObject)
        {
            //[FromBody] DataTablesRootObject dataTablesRootObject
            DataTablesResponse r = new DataTablesResponse();
            try
            {
                string searchText = "";
                if (dataTablesRootObject.search != null)
                {
                    searchText = dataTablesRootObject.search.value;
                }


                #region single sort code
                string sortInformAtion = "";

                if (dataTablesRootObject.order != null && dataTablesRootObject.order.Count > 0)
                {
                    if (dataTablesRootObject.columns != null && dataTablesRootObject.columns.Count > 0)
                    {
                        sortInformAtion = "ORDER BY " + dataTablesRootObject.columns[dataTablesRootObject.order[0].column].data + " " + dataTablesRootObject.order[0].dir;
                    }
                    //dataTablesRootObject.order[0].column
                }
                if (string.IsNullOrEmpty(sortInformAtion))
                {
                    sortInformAtion = "ORDER BY " + dataTablesRootObject.columns[0].data + " asc";
                }
                #endregion

                string error = "";
                List<DataModel.Setup.ClientListoListAll = serviceClientlist.GetsForGrid(dataTablesRootObject.startdataTablesRootObject.lengthsortInformAtionref errorsearchText);

                r.data = oListAll;

                r.draw = dataTablesRootObject.draw;
                r.error = error;
                if (oListAll != null && oListAll.Count > 0)
                {
                    r.recordsTotal = oListAll[0].RecordCount;
                    r.recordsFiltered = oListAll[0].RecordFilter;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + ex.StackTrace);
            }
            return r;

        }


When table is not refresing after data added then add following code


Add trigger in html page

<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" id="user-table"
                   class="table table-responsive-sm table-bordered table-striped table-sm">

Type Script code

implements AfterViewInit
 
declaration code

@ViewChild(DataTableDirective)
  dtElement: DataTableDirective;
dtTrigger: Subject<TempRChallan= new Subject();
 



  ngAfterViewInit(): void {
    this.dtTrigger.next();
  }

  //ngOnDestroy(): void {
  //   Do not forget to unsubscribe the event
  //  this.dtTrigger.unsubscribe();
  //}

  rerender(): void {
    this.dtElement.dtInstance.then((dtInstance: DataTables.Api=> {
      // Destroy the table first
      dtInstance.destroy();
      // Call the dtTrigger to rerender again
      this.dtTrigger.next();
    });
  }

Call rerender method for table data reload.

C# .NET Cross-thread operation not valid: Control

Monday, November 4, 2019 Category : 1

Invoke(new Action(() =>
                            {
                                //progressBar1.Value = newValue;
                           


                            }));

Powered by Blogger.