Search results

Sorting

Sorting enables you to sort data in the Ascending or Descending order. To sort a column, click the column header.

To enable sorting in the Grid, set the AllowSorting to true. Sorting options can be configured through the SortSettings.

tagHelper
sorting.cs
<ejs-grid id="Grid" dataSource="ViewBag.datasource"  allowSorting="true" height="270"> 
    
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" type="number" textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="EmployeeID" headerText="Customer ID"  width="150"></e-grid-column>
        <e-grid-column field="ShipCity" headerText="Ship City"  width="150"></e-grid-column>
        <e-grid-column field="ShipName" headerText="Ship Name"  width="150"></e-grid-column>
    </e-grid-columns>
</ejs-grid>
public IActionResult Index()
        {
            var orders=OrderDetails.GetAllRecords();
            ViewBag.datasource = orders;            
            return View();
        }
  • Grid columns are sorted in the Ascending order. If you click the already sorted column, the sort direction toggles.
  • You can apply and clear sorting by invoking sortColumn and clearSorting methods.
  • To disable sorting for a particular column, set the Columns.AllowSorting to false.

Initial sort

To sort at initial rendering, set the Field and Direction in the SortSettings.Columns.

tagHelper
initial-sort.cs
@{
               List<object> cols = new List<object>();
                cols.Add(new { field = "OrderDate", direction = "Ascending" });
                cols.Add(new { field = "Freight", direction = "Descending" });
    }
  <ejs-grid id="Grid" dataSource="ViewBag.datasource"   allowSorting="true" allowPaging="true">
            <e-grid-pagesettings pageCount="2"></e-grid-pagesettings>
            <e-grid-sortsettings columns="cols"></e-grid-sortsettings>
            <e-grid-columns>
                <e-grid-column field="OrderID" headerText="Order ID" textAlign="Right" width="120"></e-grid-column>
                <e-grid-column field="CustomerID" headerText="Customer Name" width="150"></e-grid-column>
                <e-grid-column field="OrderDate" headerText=" Order Date" textAlign="Right" format="yMd" width="130"></e-grid-column>
                <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column>                
                <e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column>
            </e-grid-columns>
</ejs-grid>
public IActionResult Index()
        {
            var orders=OrderDetails.GetAllRecords();
            ViewBag.datasource = orders;            
            return View();
        }

Multi-column sorting

You can sort more than one column in a Grid. To sort multiple columns, press and hold the CTRL key and click the column header. The sorting order will be displayed in the header while performing multi-column sorting.

To clear sorting for a particular column, press the “Shift + mouse left click”.

The AllowSorting must be true while enabling multi-column sort. Set AllowMultiSorting property as false to disable multi-column sorting.

tagHelper
multi-column-sort.cs
<ejs-grid id="Grid" dataSource="ViewBag.datasource" allowSorting="true" allowMultiSorting="true" height="270">
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" type="number" textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="EmployeeID" headerText="Customer ID"  width="150"></e-grid-column>
        <e-grid-column field="ShipCity" headerText="Ship City"  width="150"></e-grid-column>
        <e-grid-column field="ShipName" headerText="Ship Name"  width="150"></e-grid-column>
    </e-grid-columns>
</ejs-grid>
public IActionResult Index()
    {
        var orders=OrderDetails.GetAllRecords();
        ViewBag.datasource = orders;
        return View();
    }

Sort order

By default, the sorting order will be as ascending -> descending -> none.

When first click a column header it sorts the column in ascending. Again click the same column header, it will sort the column in descending. A repetitive third click on the same column header will clear the sorting.

Sort foreign key column based on Text

For local data in Grid, sorting will be performed based on the Column.ForeignKeyValue.

For remote data in Grid, sorting will be performed based on the Column.ForeignKeyField instead of Column.ForeignKeyValue. To sort a column based on the displayed text and not based on the Column.ForeignKeyField, we need to handle the sorting operation at the server side.

The following code example describes the handling of sorting operation at the server side.

tagHelper
foreign-sort.cs
<ejs-grid id="Grid" load="load">
       <e-datamanager url="/OData/Items" adaptor="ODataV4Adaptor" crossdomain="true"></e-datamanager>
       <e-grid-columns>
            <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="120"></e-grid-column>
            <e-grid-column field="EmployeeID" headerText="First Name" foreignKeyField="EmployeeID" foreignKeyValue="FirstName" width="150"></e-grid-column>               
            <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column>               
            <e-grid-column field="ShipName" headerText="Ship Name" width="150"></e-grid-column>
        </e-grid-columns>
     </ejs-grid>

    <script>
        var data = new ej.data.DataManager({
            url: '/OData/Brands',
            adaptor: new ej.data.ODataV4Adaptor,
            crossDomain: true
        });
        function load(args) {
            for (var i = 0; i < this.getColumns().length; i++) {
                if (this.getColumns()[i].foreignKeyField) {
                    this.getColumns()[i].dataSource = data;
                }
            }
        }
    </script>
public class ItemsController : ODataController
    {
        [EnableQuery]
        public IQueryable<Item> Get()
        {
            List<Item> GridData = JsonConvert.DeserializeObject<Item[]>(Properties.Resources.ItemsJson).AsQueryable().ToList();
            List<Brand> empData = JsonConvert.DeserializeObject<Brand[]>(Properties.Resources.BrandsJson).AsQueryable().ToList();
            var queryString = HttpContext.Current.Request.QueryString;
            var allUrlKeyValues = ControllerContext.Request.GetQueryNameValuePairs();
            string key = allUrlKeyValues.LastOrDefault(x => x.Key == "$orderby").Value;
            if (key != null)
            {
                if (key == "EmployeeID") {
                    GridData = SortFor(key); //Only for foreignKey Column ascending
                }
                else if(key == "EmployeeID desc") {
                    GridData = SortFor(key); //Only for foreignKey Column descending
                }
            }
            var count = GridData.Count();
            var data = GridData.AsQueryable();
            return data;
        }
        
        public List<Item> SortFor(String Sorted)
        {
            List<Item> GridData = JsonConvert.DeserializeObject<Item[]>(Properties.Resources.ItemsJson).AsQueryable().ToList();
            List<Brand> empData = JsonConvert.DeserializeObject<Brand[]>(Properties.Resources.BrandsJson).AsQueryable().ToList();
            if (Sorted == "EmployeeID") //check whether ascending or descending
                empData = empData.OrderBy(e => e.FirstName).ToList();
            else if(Sorted == "EmployeeID desc")
                empData = empData.OrderByDescending(e => e.FirstName).ToList();
            List<Item> or = new List<Item>();
            for (int i = 0; i < empData.Count(); i++) {
                //Select the Field matching records
                IEnumerable<Item> list = GridData.Where(pred => pred.EmployeeID == empData[i].EmployeeID).ToList();
                or.AddRange(list);
            }
            return or;
        }
    }

Sorting events

During the sort action, the grid component triggers two events. The ActionBegin event triggers before the sort action starts, and the ActionComplete event triggers after the sort action is completed. Using these events you can perform the needed actions.

tagHelper
sort-event.cs
<ejs-grid id="Grid" dataSource="ViewBag.datasource" actionComplete="sortEvent" actionBegin="sortEvent"  allowSorting="true" height="270"> 
    
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" type="number" textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="EmployeeID" headerText="Customer ID"  width="150"></e-grid-column>
        <e-grid-column field="ShipCity" headerText="Ship City"  width="150"></e-grid-column>
        <e-grid-column field="ShipName" headerText="Ship Name"  width="150"></e-grid-column>
    </e-grid-columns>
</ejs-grid>

<script>
function sortEvent(args){

      alert(args.requestType + ' ' + args.type); //custom Action
}

</script>
public IActionResult Index()
        {
            if (orders.Count() == 0)
                DataSource();
            ViewBag.datasource = orders;            
            return View();
        }

        public void DataSource()
        {
            int code = 10000;
            for (int i = 1; i < 10; i++)
            {
                orders.Add(new OrderDetails(code + 1, "ALFKI", i + 0, 2.3 * i, false, new DateTime(1991, 05, 15), "Berlin", "Simons bistro", "Denmark", new DateTime(1996, 7, 16), "Kirchgasse 6"));
                orders.Add(new OrderDetails(code + 2, "ANATR", i + 2, 3.3 * i, true, new DateTime(1990, 04, 04), "Madrid", "Queen Cozinha", "Brazil", new DateTime(1996, 9, 11), "Avda. Azteca 123"));
                orders.Add(new OrderDetails(code + 3, "ANTON", i + 1, 4.3 * i, true, new DateTime(1957, 11, 30), "Cholchester", "Frankenversand", "Germany", new DateTime(1996, 10, 7), "Carrera 52 con Ave. Bolívar #65-98 Llano Largo"));
                orders.Add(new OrderDetails(code + 4, "BLONP", i + 3, 5.3 * i, false, new DateTime(1930, 10, 22), "Marseille", "Ernst Handel", "Austria", new DateTime(1996, 12, 30), "Magazinweg 7"));
                orders.Add(new OrderDetails(code + 5, "BOLID", i + 4, 6.3 * i, true, new DateTime(1953, 02, 18), "Tsawassen", "Hanari Carnes", "Switzerland", new DateTime(1997, 12, 3), "1029 - 12th Ave. S."));
                code += 5;
            }
        }

The args.requestType is the current action name. For example, in sorting the args.requestType is ‘sorting’.

Touch interaction

When you tap the grid header on touchscreen devices, the selected column header is sorted. A popup sorting is displayed for multi-column sorting. To sort multiple columns, tap the popupmsorting, and then tap the desired grid headers.

The AllowMultiSorting and AllowSorting should be true then only the popup will be shown.

The following screenshot shows grid touch sorting.

Touch interaction