Sorting in ASP.NET MVC Data Grid

3 Sep 202624 minutes to read

The Syncfusion ASP.NET MVC Data Grid provides flexible sorting capabilities that help organize, analyze, and locate information efficiently. Sorting can be applied through column headers or customized to support application-specific ordering requirements.

To enable sorting in the grid, set the AllowSorting property to true.

Sorting a particular column is accomplished by clicking on its column header. Each click on the header toggles the sort order between Ascending and Descending.

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowSorting().Height("348px").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("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
}).Render()
public IActionResult Index()
{
  ViewBag.dataSource = OrderDetails.GetAllRecords();           
  return View();
}

Sorting

  • Data Grid column sorted in Ascending order. If a click occurs on an already sorted column, the sort direction toggles.
  • Apply and clear sorting by using the sortColumn and clearSorting methods.
  • To disable sorting for a specific column, set the Columns.AllowSorting property to false.

Sort order

By default, the sorting order is “ascending → descending → none”.

The first click on a column header sorts the column in ascending order. A second click sorts the column in descending order. A third click clears the sorting.

The AllowUnsort property controls whether sorting can be cleared. When set to false, clicking a grid header will only toggle between ascending and descending order, without switching to an unsorted state. The default value is true.

Initial sorting

The Data Grid component provides an option to apply initial sorting by setting the SortSettings.Columns property to the desired Field and sort Direction. This feature is useful for displaying data in a specific order when the grid initially loads.

The following example demonstrates setting SortSettings.Columns for “Order ID” and “Ship City” columns with a specified Direction.

@{
  List<object> sortOptions = new List<object>();
  sortOptions.Add(new { field = "OrderID", direction = "Ascending" });
  sortOptions.Add(new { field = "ShipCity", direction = "Descending" });
}
@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowSorting().Height("348px").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("ShipCity").HeaderText("Ship City").Width("170").Add();
  col.Field("ShipName").HeaderText("Ship Name").Width("170").Add();
}).SortSettings(sort => sort.Columns(sortOptions)).Render()
public IActionResult Index()
 {
   ViewBag.dataSource = OrderDetails.GetAllRecords();           
   return View();
 }

Sorting

The initial sorting defined in SortSettings.Columns will override any sorting applied through individual interaction.

Multi-column sorting

The Data Grid supports multi-column sorting, allowing records to be ordered using multiple sorting criteria simultaneously. Multi-column sorting makes it possible to establish hierarchical sort priorities, ensuring that records with identical values in one column can be further organized using additional columns.

To enable multi-column sorting, set the AllowSorting and the AllowMultiSorting properties to true. This enables sorting of multiple columns by holding the CTRL key and clicking the column headers. This feature is useful for datasets that require more than a single sorting dimension.

To clear multi-column sorting for a particular column, press Shift while clicking the column header.

@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowSorting().Height("348px").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("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
}).Render()
public IActionResult Index()
{
   ViewBag.dataSource = OrderDetails.GetAllRecords();           
   return View();
}

Sorting

Disable sorting for a specific column

The Data Grid component allows disabling sorting for a column. This is useful when certain columns should not be included in the sorting process.

This is achieved by setting the AllowSorting property of the particular column to false. The following example demonstrates disabling sorting for “Customer ID” column.

@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.datasource).Height("348px").AllowSorting().Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer Name").AllowSorting(false).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("ShipCity").HeaderText("Ship City").Width("170").Add();
}).Render()
public IActionResult Index()
{
  ViewBag.dataSource = OrderDetails.GetAllRecords();           
  return View();
}

Custom sorting

The Data Grid supports custom sorting through the Column.SortComparer property, providing complete control over how values are ordered within a column.

Custom sorting can be used when the required sort order differs from standard alphabetical or numerical sorting. This is useful for scenarios that require custom rankings, status-based ordering, priority sequencing, locale-aware comparisons, display-value sorting, or specialized handling of null values.

The following example demonstrates defining a custom SortComparer function for the “Customer ID” column.

@{
    Object sortComparer = "sortComparer";
}
@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowSorting().Height("348px").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").SortComparer("sortComparer").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("ShipCity").HeaderText("Ship City").Width("170").Add();
}).Render()
<script>
    function sortComparer(reference, comparer){
        if (reference < comparer) {
            return -1;
        }
        if (reference > comparer) {
            return 1;
        }
        return 0;
    }
</script>
public IActionResult Index()
{
  ViewBag.dataSource = OrderDetails.GetAllRecords();           
  return View();
}

Sorting

The “customSortComparer” function takes two parameters: a and b, which are the values being compared. The function returns “-1”, “0”, or “1”, depending on the comparison result.

Display null values always at bottom

By default, “null” values in a ASP.NET MVC Data Grid are displayed at the top when sorting in descending order and at the bottom when sorting in ascending order. However, “null” values can be configured to always display at the bottom of the grid regardless of sort direction. This is achieved by utilizing the Column.SortComparer method. This feature is particularly useful when working with data sets where “null” values might need to be clearly separated from actual data entries.

The example below demonstrates displaying “null” values at the bottom of the grid while sorting the “Order Date” column in both ascending and descending order.

@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowSorting().Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("100").Add();
   col.Field("CustomerID").HeaderText("Customer ID").Width("120").Add();
   col.Field("OrderDate").HeaderText("Order Date").Format("yMd").SortComparer("sortComparer").Width("130").Add();
   col.Field("ShipCountry").HeaderText("ShipCountry").Width("150").Add();
}).ActionBegin("actionBegin").Render()
<script type="text/javascript">
    var action;
    function actionBegin(args) {
        if (args.requestType == "sorting") {
            action = args.direction;
        }
    }
    function sortComparer(reference, comparer) {
        var sortAsc = action === "Ascending" ? true : false;
        if (sortAsc && reference === null) {
            return 1;
        }
        else if (sortAsc && comparer === null) {
            return -1;
        }
        else if (!sortAsc && reference === null) {
            return -1;
        }
        else if (!sortAsc && comparer === null) {
            return 1;
        } else {
            return reference - comparer;
        }
    }
</script>
public IActionResult Index()
{
    ViewBag.dataSource =OrderDetails.GetAllRecords();
    return View();
}

Sorting

Foreign key sorting

Foreign-key sorting enables sorting based on displayed values rather than the underlying identifier values stored in the data source.

To sort a foreign key column based on its displayed text, the foreign key column can be enabled by using Column.DataSource, Column.ForeignKeyField and Column.ForeignKeyValue properties.

Sort foreign key column based on text for local data

When working with local data in the grid, sorting is performed based on the ForeignKeyValue defined in the column. This field should be specified in the column definition with the corresponding foreign key value for each row. The grid then sorts the foreign key column according to the text representation of that value.

The following example demonstrates sorting with a foreign key column enabled, where the “Customer ID” column acts as a foreign column displaying the “Contact Name” column from foreign data.

@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowSorting().Height("348px").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").ForeignKeyValue("ContactName").ForeignKeyField("CustomerID").DataSource((IEnumerable<object>)ViewBag.customerData).Add();
    col.Field("ShipCity").HeaderText("Ship City").Width("170").Add();
    col.Field("ShipName").HeaderText("Ship Name").Width("170").Add();
}).Render();
public IActionResult Index()
{
  ViewBag.dataSource = OrderDetails.GetAllRecords();
  ViewBag.customerData= EmployeeData.GetAllRecords()           
  return View();
}

Sorting

Sort foreign key column based on text for remote data

In the case of remote data in the grid, the sorting operation will be performed based on the ForeignKeyField property of the column. The ForeignKeyField property should be defined in the column definition with the corresponding foreign key field name for each row. The grid will send a request to the server-side with the ForeignKeyField name, and the server-side should handle the sorting operation and return the sorted data to the grid.

The following example demonstrates sorting a foreign key column where the “Employee ID column is a foreign key, and the corresponding “First Name column is displayed from the employee data source:

@Html.EJS().Grid("grid").DataSource(ds => ds.Url(@Url.Action("GetOrderRecords", "Home")).Adaptor("UrlAdaptor")).Height("348px").Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("EmployeeID").HeaderText("Employee Name").ForeignKeyField("EmployeeID").ForeignKeyValue("FirstName").DataSource(ds => ds.Url(@Url.Action("GetEmployeeRecords", "Home")).Adaptor("UrlAdaptor")).Width("140").Add();
    col.Field("CustomerID").HeaderText("Customer ID").Width("150").Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("ShipName").HeaderText("Ship Name").Width("160").Add();
}).AllowSorting(true).AllowPaging(true).Render()
public ActionResult Index()
{
  return View();
}

public ActionResult GetEmployeeRecords()
{
  IEnumerable employeeData = EmployeeView.GetAllRecords();
  return Json(employeeData);
}

public ActionResult GetOrderRecords(DataManagerRequest request)
{
  IEnumerable orderData = OrdersDetails.GetAllRecords();
  DataOperations dataOperations = new DataOperations();
  if (request.Sorted != null && request.Sorted.Count > 0)
  {
    string sortColumn = request.Sorted[0].Name;
    string sortDirection = request.Sorted[0].Direction;
    if (sortColumn == "EmployeeID")
    {
      orderData = GetSortedOrdersByEmployee(sortDirection);
    }
    else
    {
      orderData = dataOperations.PerformSorting(orderData, request.Sorted);
    }
  }
  int totalRecords = orderData.Cast<OrdersDetails>().Count();
  if (request.Skip != 0)
  {
    orderData = dataOperations.PerformSkip(orderData, request.Skip);
  }
  if (request.Take != 0)
  {
    orderData = dataOperations.PerformTake(orderData, request.Take);
  }
  return request.RequiresCounts ? Json(new { result = orderData, count = totalRecords }) : Json(orderData);
}

private List<OrdersDetails> GetSortedOrdersByEmployee(string sortDirection)
{
  var employees = EmployeeView.GetAllRecords();
  List<EmployeeView> sortedEmployees = (sortDirection == "ascending")
    ? employees.OrderBy(e => e.FirstName).ToList()
    : employees.OrderByDescending(e => e.FirstName).ToList();

  List<OrdersDetails> sortedOrders = new List<OrdersDetails>();
  foreach (var employee in sortedEmployees)
  {
    var employeeOrders = OrdersDetails.GetAllRecords().Where(o => o.EmployeeID == employee.EmployeeID).ToList();
    sortedOrders.AddRange(employeeOrders);
  }
  return sortedOrders;
}

Sorting

Culture-based sorting

Culture-based sorting applies locale-specific comparison rules, ensuring accurate sorting behavior for multilingual and internationalized applications.

Culture-specific sorting is achieved by utilizing the Locale property. By setting the Locale property to the desired culture code, sorting is enabled based on that specific culture.

In the following example, sorting is performed based on the “ar” locale using the Column.SortComparer property.

@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowSorting().Height("348px").Locale("ar").Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).SortComparer("sortComparer").Add();
    col.Field("CustomerID").HeaderText("Customer Name").Width("170").SortComparer("sortComparer").Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).SortComparer("sortComparer").Add();
    col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yyyy/MMM/dd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).SortComparer("sortComparer").Add();
}).Render()
<script>
    loadCultureFiles('en-US');
    ej.base.setCulture('ar');
    ej.base.setCurrencyCode('QAR');
    function loadCultureFiles(name) {
        var files = ['ca-gregorian.json', 'currencies.json', 'numberingSystems.json', 'numbers.json', 'timeZoneNames.json', 'currencies.json'];
        var loader = ej.base.loadCldr;
        var loadCulture = function (prop) {
            var value, ajax;
            ajax = new ej.base.Ajax(location.origin + '/../Content/cldr-data/main/' + name + '/' + files[prop], 'GET', false);
            ajax.onSuccess = function (value) {
                value = value;
                ej.base.loadCldr(JSON.parse(value));
            };
            ajax.send();
        };
        for (var prop = 0; prop < files.length; prop++) {
            loadCulture(prop);
        }
    }
    function sortComparer(reference, comparer, sortOrder) {
        const referenceDate = new Date(reference);
        const comparerDate = new Date(comparer);
        if (typeof reference === 'number' && typeof comparer === 'number') {
            return sortOrder === 'Ascending' ? comparer - reference : reference - comparer;
        } else if (!isNaN(referenceDate.getTime()) && !isNaN(comparerDate.getTime())) {
            return sortOrder === 'Ascending' ? comparerDate.getTime() - referenceDate.getTime() : referenceDate.getTime() - comparerDate.getTime();
        }
        else {
            const stringComparator = new Intl.Collator(undefined, { sensitivity: 'variant', usage: 'sort' });
            const comparisonResult = stringComparator.compare(String(reference), String(comparer));
            return sortOrder === 'Ascending' ? -comparisonResult : comparisonResult;
        }
    };
</script>
public IActionResult Index()
{
  ViewBag.dataSource = OrderDetails.GetAllRecords();           
  return View();
}

Sorting

Touch interaction

On touch devices, tapping a grid header sorts that column Sorting.
For multi‑column sorting, tap the sorting indicator Multi Sorting and then tap the additional grid headers to include them in the sort order.

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

The following screenshot represents a grid touch sorting in the device.

Touch Interaction

Programmatic sorting

The Data Grid component in Syncfusion’s ASP.NET MVC suite allows customization of column sorting and provides flexibility in sorting based on external interactions. Sort columns, remove a sort column, and clear sorting using an external button click.

Add sort columns

External column sorting is accomplished using the sortColumn method with parameters columnName, direction, and isMultiSort. This method enables programmatic sorting of a specific column based on specified requirements.

The following example demonstrates adding sort columns to a grid. The DropDownList component selects the column and sort direction. When an external button is clicked, the sortColumn method is called with the specified columnName, direction, and isMultiSort parameters.

@{
    ViewBag.dropDownData = new List<object>
    {
         new { value = "OrderID", text = "Order ID" },
         new { value = "CustomerID", text = "Customer ID" },
         new { value = "Freight", text = "Freight" },
         new { value = "ShipName", text = "Ship Name" }
    };
    ViewBag.directionData = new List<object>
    {
         new { value = "Ascending", text = "Ascending" },
         new { value = "Descending", text = "Descending" }
    };
    List<object> sortOptions = new List<object>();
    sortOptions.Add(new { field = "ShipName", direction = "Ascending" });
 }
<div style="padding-bottom:20px">
    <div style="display: flex">
        <label style="padding: 5px 28px 0 0"> Column name :</label>
        <span style="height:fit-content">
            @Html.EJS().DropDownList("dropDownColumn").Width("120px").Index(3).DataSource(@ViewBag.dropDownData).Fields(new Syncfusion.EJ2.DropDowns.DropDownListFieldSettings { Value = "value", Text = "text" }).Render()
        </span>
    </div>
    <div style="display: flex; padding-top: 20px; ">
        <label style="padding: 5px 10px 0 0"> Sorting direction :</label>
        <span style="height:fit-content">
            @Html.EJS().DropDownList("dropDownDirection").Width("120px").Index(0).DataSource(@ViewBag.directionData).Render()
        </span>
    </div>
    <div style="margin-top: 10px; margin-left: 130px">
        @Html.EJS().Button("sortButton").CssClass("e-primary").Content("Add sort column").Render()
    </div>
</div>
@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Height("348px").AllowSorting(true).Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer ID").Width("170").Add();
    col.Field("ShipCity").HeaderText("Ship City").Width("170").Add();
    col.Field("ShipName").HeaderText("Ship Name").Width("170").Add();
}).SortSettings(sort => sort.Columns(sortOptions)).Render()
<script>
    document.getElementById('sortButton').addEventListener('click', function () {
        var grid = document.getElementById("grid").ej2_instances[0];
        grid.sortColumn(
            document.getElementById("dropDownColumn").ej2_instances[0].value,
            document.getElementById("dropDownDirection").ej2_instances[0].value,
            true
        );
    });
</script>
public IActionResult Index()
{
  ViewBag.dataSource = OrderDetails.GetAllRecords();           
  return View();
}

Sorting

Remove sort columns

External removal of sort columns is accomplished using the removeSortColumn method provided by the Data Grid component. This method removes the sorting applied to a specific column.

The following example demonstrates removing sort columns. The DropDownList component selects the column. When an external button is clicked, the removeSortColumn method removes the selected sort column.

@{
    ViewBag.dropDownData = new List<object>
    {
        new { value = "OrderID", text = "Order ID" },
        new { value = "CustomerID", text = "Customer ID" },
        new { value = "ShipCity", text = "Ship City" },
        new { value = "ShipName", text = "Ship Name" }
    };
    List<object> sortOptions = new List<object>();
    sortOptions.Add(new { field = "CustomerID", direction = "Ascending" });
    sortOptions.Add(new { field = "ShipName", direction = "Descending" });
}
<div style="padding-bottom:20px">
    <div style="display: flex">
        <label style="padding: 5px 28px 0 0;font-weight: bold;"> Column name :</label>
        <span style="height:fit-content">
            @Html.EJS().DropDownList("dropDownColumn").Width("120px").Index(0).DataSource(@ViewBag.dropDownData).Fields(new Syncfusion.EJ2.DropDowns.DropDownListFieldSettings { Value = "value", Text = "text" }).Render()
        </span>
    </div>
    <div style="margin-top: 10px; margin-left: 125px">
        @Html.EJS().Button("removeButton").CssClass("e-primary").Content("Remove sort column").Render()
    </div>
</div>
@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Height("348px").AllowSorting(true).Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer ID").Width("170").Add();
    col.Field("ShipCity").HeaderText("Ship City").Width("170").Add();
    col.Field("ShipName").HeaderText("Ship Name").Width("170").Add();
}).SortSettings(sort => sort.Columns(sortOptions)).Render();
<script>
    document.getElementById('removeButton').addEventListener('click', function () {
        var grid = document.getElementById("grid").ej2_instances[0];
        var value = document.getElementById("dropDownColumn").ej2_instances[0].value;
        grid.removeSortColumn(value);
    });
</script>
public IActionResult Index()
{
  ViewBag.dataSource = OrderDetails.GetAllRecords();           
  return View();
}

Sorting

Clear sorting

Sorting is cleared on an external button click using the clearSorting method provided by the grid component. This method clears the sorting applied to all columns in the grid.

The following example demonstrates clearing sorting using the clearSorting method in an external button click.

@{
    List<object> sortOptions = new List<object>();
    sortOptions.Add(new { field = "CustomerID", direction = "Ascending" });
    sortOptions.Add(new { field = "ShipName", direction = "Descending" });
}
<div style="padding-bottom:20px">
    @Html.EJS().Button("clearButton").CssClass("e-primary").Content("Clear Sorting").Render()
</div>
@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Height("348px").AllowSorting(true).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("ShipCity").HeaderText("Ship City").Width("170").Add();
    col.Field("ShipName").HeaderText("Ship Name").Width("170").Add();
}).SortSettings(sort => sort.Columns(sortOptions)).Render()
<script>
    document.getElementById('clearButton').addEventListener('click', function () {
        var grid = document.getElementById("grid").ej2_instances[0];
        grid.clearSorting();
    });
</script>
public IActionResult Index()
{
  ViewBag.dataSource = OrderDetails.GetAllRecords();           
  return View();
}

Sorting

Sorting events

The Data Grid component provides two events that are triggered during the sorting action such as ActionBegin and ActionComplete. These events can be used to perform any custom actions before and after the sorting action is completed.

  1. ActionBegin: ActionBegin event is triggered before the sorting action begins. It provides a way to perform any necessary operations before the sorting action takes place. This event provides a parameter that contains the current grid state, including the current sorting column, direction, and data.

  2. ActionComplete: ActionComplete event is triggered after the sorting action is completed. It provides a way to perform any necessary operations after the sorting action has taken place. This event provides a parameter that contains the current grid state, including the sorted data and column information.

This example demonstrates that the ActionBegin event is used to cancel sorting for the “Order ID” column, while the ActionComplete event displays a message after the sorting action finishes.

<div style="margin-left:100px;"><p style="color:red;" id="message"></p></div>
@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowSorting().Height("348px").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("ShipCity").HeaderText("Ship City").Width("170").Add();
    col.Field("ShipName").HeaderText("Ship Name").Width("170").Add();
}).ActionComplete("actionComplete").ActionBegin("actionBegin").Render()
<script>
    function actionBegin(args) {
        if (args.requestType === 'sorting' && args.columnName === 'OrderID') {
            document.getElementById('message').innerText = args.requestType + ' action cancelled for ' + args.columnName + ' column';
            args.cancel = true;
        }
    }
    function actionComplete(args) {
        if (args.requestType === 'sorting'&& args.columnName !== undefined) {
            document.getElementById('message').innerText = args.requestType + ' action completed for ' + args.columnName + ' column';
        }
        else {
            document.getElementById('message').innerText = "";
        }
    }
</script>
public IActionResult Index()
 {
    ViewBag.dataSource = OrdersDetails.GetAllRecords();            
    return View();
 }

Sorting

args.requestType refers to the current action being performed. For example in sorting, the args.requestType value is sorting.

Customizing the sort icon

Sort icon customization in the grid is accomplished by overriding the default grid classes .e-icon-ascending and .e-icon-descending with custom content using CSS. The desired icons or symbols are specified using the content property as shown below:

.e-grid .e-icon-ascending::before {
  content: '\e306';
}
	
.e-grid .e-icon-descending::before {
  content: '\e304';
}

The following sample demonstrates a grid rendered with a customized sort icon.

@{
  List<object> sortOptions = new List<object>();
  sortOptions.Add(new { field = "ShipCity", direction = "Ascending" });
  sortOptions.Add(new { field = "CustomerID", direction = "Descending" });
}
@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Height("348px").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("ShipCity").HeaderText("Ship City").Width("170").Add();
  col.Field("ShipName").HeaderText("Ship Name").Width("170").Add();
}).SortSettings(sort => sort.Columns(sortOptions)).Render()
<style>
    .e-grid .e-icon-ascending::before {
        content: '\e822';
    }
    .e-grid .e-icon-descending::before {
        content: '\e7fe';
    }
</style>
public IActionResult Index()
{
   ViewBag.dataSource = OrderDetails.GetAllRecords();           
   return View();
}

Sorting

See Also