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/.
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.
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.
<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
.
<script>
$(document).ready(function () {
$("#GridView1").tablesorter({
sortList: [[0, 0], [2, 1]],
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:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
onsorting="GridView1_Sorting">
</asp:GridView>
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.
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.
Add a action method to get jsonResult
as below to home controller.
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.
<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.
<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.
<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.
<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.