Introduction
In this article, I will examine how to build custom sorting using Jquery UI. The jQuery UI Sortable plugin makes selected elements sortable by dragging with the mouse. Please see here for more details. In my demo application, I will create an XML file to store the custom settings that will hold the sorting order.
Using the Code
Here is our XML File:
="1.0"="utf-8"
<customers>
<customer>
<id>1001</id>
<name>Microsoft</name>
<address>One Microsoft Way</address>
<sortorder>4</sortorder>
</customer>
<customer>
<id>1002</id>
<name>Google</name>
<address>Mountain View, CA</address>
<sortorder>5</sortorder>
</customer>
<customer>
<id>1003</id>
<name>Amazon</name>
<address>Seattle, WA</address>
<sortorder>2</sortorder>
</customer>
<customer>
<id>1004</id>
<name>IBM</name>
<address>Armonk, New York</address>
<sortorder>3</sortorder>
</customer>
<customer>
<id>1005</id>
<name>Yahoo</name>
<address>Sunnyvale, California</address>
<sortorder>1</sortorder>
</customer>
</customers>
I will create a simple web form application to demonstrate custom sorting. If you want to use ASP.NET MVC, then please see JQuery AJAX with ASP.NET MVC.
To create a web application, please follow these steps:
- Launch Visual Studio 2005 or 2008.
- Click on File -> new -> project, then select ASP.NET web application.
- It will create a basic web application template for us.
Here is our default.aspx page:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="CustomSort._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Sortable Demo</title>
<script type="text/javascript"
src="http://www.google.com/jsapi"></script>
<script language="javascript" type="text/javascript">
google.load("jquery", "1.3.2");
google.load("jqueryui", "1.7.2");
</script>
<script type="text/javascript"
src="http://www.json.org/json2.js"></script>
<SCRIPT type=text/javascript>
$(function() {
$("#sortable").sortable();
$("#sortable").disableSelection();
});
function update() {
var list = new Array();
$("ul").each(function(index, id) {
var result = $('#' + id.id).sortable('toArray');
var j = 0;
for (var i = 0; i < result.length; i++) {
list[j++] = $('#' + result[i])[0].value;
}
});
var jsonText = JSON.stringify({ list: list });
$.ajax({
type: "POST",
url: "Default.aspx/SaveData",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(res) {
$("#divResult").text(res.d);
}
});
}
</SCRIPT>
<style type="text/css">
ul.horizontal_list li{
text-align:left;
list-style: none;
padding: 3px 10px 3px 10px;
margin: 5px;
border: 1px solid #CCC;
width: 250px;
cursor : move;
}
</style>
</head>
<body>
<div id="divResult" style="color:red;"></div>
<asp:Panel ID="spaceHolder" runat="server" ></asp:Panel>
<input type="button" value="Update" onclick="javascript:update();" />
</body>
</html>
In the above code:
- Our page is loading JQuery and JQuery UI from Google hosted AJAX libraries API as it will improve the site performance. Please see here for more details.
- Our page is also loading utility class from json.org that has a method
JSON.stringify(value)
that takes a JavaScript value and produces a JSON text. - We are using Jquery sortable UI plugin to read user defined sorting order. Please see here for more details.
- Our page makes jquery AJAX call using an HTTP
POST
request. - It passes user defined sortorder data in JSON format to
[WebMethod]
as shown below.
Here is our code behind Default.aspx.cs:
namespace CustomSort
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
XDocument users = XDocument.Load(Server.MapPath("~/App_Data/Data.xml"));
var query = from user in users.Elements("customers").Elements("customer")
orderby user.Element("sortorder").Value
select user;
StringBuilder sb = new StringBuilder();
int liCounter = 0;
sb.Append("<ul id=\"sortable\" class=\"horizontal_list\"
style=\"list-style-type:none;margin-left:10px;\">");
foreach (XElement usr in query)
{
sb.AppendFormat("<li id=\"itemID{0}\" value=\"{1}\">",
liCounter++, usr.Element("id").Value);
sb.AppendFormat("{0},{1}</li>", usr.Element("name").Value, usr.Element("address").Value);
}
sb.Append("</ul>");
spaceHolder.Controls.Add(new LiteralControl(sb.ToString()));
}
[WebMethod]
public static string SaveData(List<string> list)
{
string retResult = string.Empty;
try
{
XDocument xmldoc = XDocument.Load
(HttpContext.Current.Server.MapPath("~/App_Data/Data.xml"));
int sortOrder = 1;
list.ForEach(delegate(string c)
{
XElement xElement = xmldoc.XPathSelectElement
("customers/customer[id = " + c + "]/sortorder");
xElement.SetValue(sortOrder++);
});
xmldoc.Save(HttpContext.Current.Server.MapPath("~/App_Data/Data.xml"));
retResult = "Data has been saved successfully";
}
catch (Exception ex)
{
retResult = ex.Message;
}
return retResult;
}
}
}
In the above code, our SaveData
method receives Customer ID in a list as a user defined sort order. Then we use LINQ to XML to update user defined sort order in an XML file.
Here are a few screen shots for our final application:
Summary
In this article, we examined custom sorting using jQuery UI. As you can see, jQuery UI is a very powerful tool to build Web 2.0 enabled applications.
History
- 19th September, 2009: Initial post