Search results

Sorting in ASP.NET MVC Grid control

03 Aug 2021 / 3 minutes to read

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.

razor
sorting.cs
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.datasource).AllowSorting().Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer Name").Width("170").Add();
    col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

}).AllowPaging().PageSettings(page => page.PageCount(5)).Render()
Copied to clipboard
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 AllowSorting property of Column to false.

Initial sort

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

razor
initial-sort.cs
Copied to clipboard
@{
    List<object> cols = new List<object>();
    cols.Add(new { field = "OrderDate", direction = "Ascending" });
    cols.Add(new { field = "Freight", direction = "Descending" });
}

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.datasource).AllowSorting().Columns(col =>
{
  col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
  col.Field("CustomerID").HeaderText("Customer Name").Width("170").Add();
  col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
  col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
  col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();

}).AllowPaging().PageSettings(page => page.PageCount(2)).SortSettings(sort => sort.Columns(cols)).Render()
Copied to clipboard
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.

razor
multi-column-sort.cs
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.datasource).AllowSorting().AllowMultiSorting().Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer Name").Width("170").Add();
    col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

}).AllowPaging().PageSettings(page => page.PageCount(5)).Render()
Copied to clipboard
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 ForeignKeyValue property of Column.

For remote data in Grid, sorting will be performed based on the ForeignKeyField instead of ForeignKeyValue. To sort a column based on the displayed text and not based on the 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.

razor
foreign-sort.cs
Copied to clipboard
@Html.EJS().Grid("ItemGrid").DataSource(dataManger => { dataManger.Url("/OData/Items").Adaptor("ODataV4Adaptor"); }).Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign("Right").Add();
    col.Field("EmployeeID").ForeignKeyField("EmployeeID").ForeignKeyValue("FirstName").DataSource(dm => { dm.Url("/OData/Brands").Adaptor("ODataV4Adaptor"); }).HeaderText("First Name").Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign("Right").Add();
    col.Field("ShipName").HeaderText("Ship Name").Add();
    
}).AllowPaging().AllowSorting(true).AllowMultiSorting(true).Render()
Copied to clipboard
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.

razor
sort-event.cs
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.datasource).AllowSorting(true).ActionComplete("sortEvent").ActionBegin("sortEvent").Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer Name").Width("170").Add();
    col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

}).AllowPaging().PageSettings(page => page.PageCount(5)).Render()

<script>
      function sortEvent(args){
            alert(args.requestType + ' ' + args.type); //custom Action
      }
</script>
Copied to clipboard
public IActionResult Index()
 {
    ViewBag.datasource = OrdersDetails.GetAllRecords();            
    return View();
 }

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 popup msorting , 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