Click here to Skip to main content
15,867,686 members
Articles / Web Development / ASP.NET
Tip/Trick

How to Sort a Table in ASP.NET and MVC

Rate me:
Please Sign up or sign in to vote.
5.00/5 (9 votes)
26 Feb 2015CPOL3 min read 29.9K   327   6   2
This tip will explain how to sort a table / GridView on an ASP.NET or MVC(AngularJs) application. I am demonstrating both client side and server side sorting. I am sure you will have a great knowledge on this topic after reading it.

Introduction

Just download the attached solution developed in Visual studio 2010 and MVC 2.0.

Often developers will be looking for the easiest way to sort a table on ASP.NET / MVC (AngularJs) or in general any HTML page. This article is targetting those who are looking for the same first time and for those who are using AngularJs in their application.

Using the Code for ASP.NET Client Side

I am making use of tableSorter jQuery plugin for client side sorting. If you have enough time, you can dip your head in writing your own logic.

Here is the link for advanced information. http://tablesorter.com/docs/.

Image 1

Create an ASP.NET empty project and add a .ASPX page.

Drag and drop a GridView from tool box.

Add the below cade to DataBound event of GridView. This will add <thead>, <tbody> and <tfoot> tags to table.
To use tableSorter jQuery plugin, it is must to have <thead> section. GridView by default will not render <thead> tag.

C#
protected void GridView1_DataBound(object sender, EventArgs e)
        {         
            if (this.GridView1.Rows.Count > 0)
            {
                GridView1.UseAccessibleHeader = true;
                GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
                GridView1.FooterRow.TableSection = TableRowSection.TableFooter;
            }
        }

In Head section of aspx file, add the below style and JavaScript file reference.

HTML
<link href="Style/blue/style.css" rel="stylesheet" type="text/css" />
    <link href="Style/green/style.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/jquery-latest.js" type="text/javascript"></script>
    <script src="Scripts/jquery.tablesorter.js" type="text/javascript"></script>
    <script src="Scripts/TableSorter.js" type="text/javascript"></script>

Add the below code to make table Sorter effective on gridViewId.

JavaScript
<script>
        $(document).ready(function () {

            $("#GridView1").tablesorter({
                sortList: [[0, 0], [2, 1]],//First column in ascending order. 
					// 3rd column in descending order(Group by first column.)
                widgets: 'zebra'
            });            
         });
    </script>

Add class="tablesorter" to <body> tag and CssClass="tablesorter" to <gridView> tag.

You are done..! Now table columns can be sorted in both directions.

Using the Code for ASP.NET Conventional Way

Drag and drop a GridView. Enable AllowSorting property & assign an event hadler to onsorting event as below:

HTML
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" 
            onsorting="GridView1_Sorting">
        </asp:GridView>

Image 2

Add this code in Sorting event. This code will sort the datatable stored in Viewstate and re bind to gridView again. You can send a query (with OrderBy and direction) to database if table is large.

C#
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            DataTable dt = (DataTable)ViewState["ViewGrid"];
            string dir = string.Empty;
            
            if (ViewState["SortDirection"] == null)
            {
                ViewState["SortDirection"] = "asc";
                dir = "asc";
            }
            else
            {
                ViewState["SortDirection"] = null;
                dir = "desc";
            }            
            dt.DefaultView.Sort = e.SortExpression + " " + dir;

            ViewState["ViewGrid"] = dt.DefaultView.ToTable();
            bindGridView();
        }

You are done..!

Now table columns can be sorted in both directions. But this will cause server side sorting, i.e., every time user clicks on sorting header, page will be post back. It may cause unnecessary network trafffic. But it has an added advantage if JavaScript is disabled on client's bowser.

Using the Code for MVC with AngularJs

I am using MVC 2. This technique of sorting is version invariant. In order to see the demo, please set project "MvcSortingAngularJs" as startUp project in the attached demo solution.

Image 3

Add a action method to get jsonResult as below to home controller.

C#
public JsonResult getJsonData()
        {
            List<EmployeeClass> empList = new List<EmployeeClass>()
            {
                new EmployeeClass{ empId=2, empName="ABC", empCity="Bangalore"},
                new EmployeeClass{ empId=1, empName="BCD", empCity="Chennai"},
                new EmployeeClass{ empId=4, empName="CDE", empCity="New York"},
                new EmployeeClass{ empId=4, empName="XYZ", empCity="New Delhi"},
                new EmployeeClass{ empId=5, empName="PQR", empCity="Mysore"}
            };
            return Json(empList, JsonRequestBehavior.AllowGet);
        }

On the Head section of the view, give a reference to AngularJs CDN.

HTML
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

Additionally, I am using bootstrap.css to generate some good look and feel.

Add a JavaScript function to get json data from Controller action (Home/getJsonData). Here, I am also assigning user defined property 'Predicate' to first column. This will act as default sorted column.

JavaScript
<script>
        function testController($scope, $http) {

            $http.get("/Home/getJsonData")
            .success(function (res) {
                $scope.details = res;
                $scope.predicate = 'empId';
            });
        }
    </script>

This JavaScript function acts as controller of angularJs as we mention it in ng-controller attribute and we will generate a table row for each employee object.

HTML
<tr ng-repeat="y in details | orderBy:predicate:reverse">
    <td>
        <button class="btn" ng-click="editUser(y.empId)">
            <span class="glyphicon glyphicon-pencil"></span>Edit
        </button>
    </td>
    <td>{{y.empId}}</td><td>{{y.empName}}</td><td>{{y.empCity}}</td>
</tr>               

In the <thead> section, we will add the below code to reverse the sorting order each time a user clicks on it.

HTML
<thead>
   <tr>
      <th>Edit</th><th><a href='#'
      ng-click="predicate='empId'; reverse=!reverse">ID</a>
      </th>
      <th>
         <a href='#' ng-click="predicate='empName'; reverse=!reverse">Employee Name</a>
      </th>
      <th>
         <a href='#' ng-click="predicate='empCity';reverse=!reverse">Employee City</a>
      </th>
   </tr>
</thead>

That's it. You are done!

Now table can be sorted at client side in both directions. Note that AngularJs is just one of the ways. You can use TableSorter plugin if you are not using AngularJs.

So simple? Please rate this tip and comment if there are any updates.

Thanks.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionError Pin
Eren Alkan 20224-May-22 9:32
Eren Alkan 20224-May-22 9:32 
GeneralMy vote of 5 Pin
Carsten V2.027-Feb-15 5:11
Carsten V2.027-Feb-15 5:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.