Sortable List using ASP.net MVC and jQuery

Sorting is one of the most basic and essential algorithm form the early days of computation, In this article we will be discussing about sorting a list of items in a web application, this is one of the common feature given to the administrators, for example sorting the products in an e-commerce application, FAQ list etc etc, I am using the feature list as an example, typically this will be like features of a product which a web admin would like to sort.

Code:

Lets start by opening an ASP.net MVC application.

TDD:

ASP.net MVC gives a lot of emphasis on test driven development and its always a good practice to write a test before implementing any solution which will serve as a guideline for us at the time of implementing the functionality so lets add a test which will ensure that all the items are sorted according to their position after the list is sorted.

[TestMethod]
public void PositionsShouldBeSortedAfterSortList()
{
var features = new List
{
new Feature {Id = 1, Description = “Feature1”, Position = 1},
new Feature {Id = 2, Description = “Feature2”, Position = 3},
new Feature {Id = 3, Description = “Feature3”, Position = 7},
new Feature {Id = 4, Description = “Feature4”, Position = 2},
new Feature {Id = 5, Description = “Feature5”, Position = 11}
};
var modifiedOrder = new List { 32415 };
var sortedPositions = features
.OrderBy(> f.Position)
.Select(> f.Position)
.ToList();

FeatureService.SortList(features, modifiedOrder, sortedPositions);
var lastPosition = 0;

foreach (var order in modifiedOrder)
{
var position = features.Single(> f.Id == order).Position;
Assert.IsTrue(position > lastPosition);
lastPosition = position;
}

}

Database:

lets add a database to our application then add the table to hold the features of the product, the schema would be similar to this

the important thing to notice in this table is the “Position” column which will hold the sort position of each item, on the first sight it would seem like a nice candidate for an Identity key but bear in mind that this field is updateable, so implement your own mechanism to decide the value of position when creating a new item. Add few items to this table.

Model:

you can create the model with any technology of your preference, for this example lets implement the model using Linq2Sql, the generated model will be like this

Model

Controller:

to keep it simple lets modify the index action of the Home Controller to fetch the list items and hand it over to the View

public ActionResult Index()
{
var db = new DbDataContext();
var features = db.Features.OrderBy( f > f.Position);
return View(features);
}

View:

<ul id=“features”> <%foreach (var feature in (IEnumerable)Model) { %>
    <li id=“<%=”feature_” + feature.Id “> <%=feature.Description></li>
<%} %></ul>

the key thing to notice here is the id of the “li” element it should have an underscore within it which will be used by the library to fetch the ids in the order in which they were sorted

JavaScript:

we will be using the jQuery and thejQuery.ui libraries, jQuery is already a part of the ASP.net MVC project template so it will be in the Scripts folder, download the jQuery.ui script and add it to the Script folder and add a reference in your Site.Master.

<script src=“<%=ResolveUrl(“~/Scripts/jquery-1.3.2.min.js”) %>” type=“text/javascript”></script>
<script src=“<%=ResolveUrl(“~/Scripts/jquery-ui.js”) %>” type=“text/javascript”></script>

in the index page add the following javascript

<script type=“text/javascript”>
          $(function() {             
                           $(‘#features’).sortable();         
                       });
</script>

in the index page add the following javascript

<script type=“text/javascript”>
    $(function() {
        $(‘<img src=”<%=ResolveClientUrl(“~/Content/arrow.png”)%> alt= “move” class=”handle” />’).prependTo(‘#features li’);
        $(‘#features’).sortable({
            opacity: 0.7,
            revert: true,
            scroll: true,
            handle: ‘.handle’
            }
        });
    });
</script>

this will make the list sortable in the client side, but the user experience is not so good and the important piece of saving the position information to the database is still not implemented, to add a better user experience lets add an image to each list item which will be used as an handle to drag our items, its not a good idea to add this image in the markup as its not semantic so we can harness the power of jQuery to add this image, after that lets add some more options to the sortable method to improve the UX.

<script type=“text/javascript”>
    $(function() {
        $(‘<img src=”<%=ResolveClientUrl(“~/Content/arrow.png”)%> alt= “move” class=”handle” />’).prependTo(‘#features li’);
        $(‘#features’).sortable({
            opacity: 0.7,
            revert: true,
            scroll: true,
            handle: ‘.handle’
            }
        });
    });
</script>

CSS:

lets add some CSS to style the list

ul#features{
list-style: none;
}
ul#features li{
margin: 0.5em;
}
ul#features li img.handle{
cursor: move;
width: 10px;
height: 10px;
}

sortable list

Saving to DB:

we come to the final part of saving the positions back to the db, for this we need to implement the ajax callback method in the sortable function called update

$(‘#features’).sortable({
opacity: 0.7,
revert: true,
scroll: true,
handle: ‘.handle’,
update: function(sorted) {
$.ajax({
url: ‘/Home/UpdatePosition’,
type: “POST”,
data: { ‘positions’: $(this).sortable(‘toArray’) }
});
}
});

after this lets add an action method in the home controller to listen to this ajax call

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdatePosition(string[] positions)
{
var db = new DbDataContext();
var modifiedOrder = new List(GetModifiedArrayIndexes(positions));
var features = db.Features.ToList();
var sortedPositions = db.Features
                                 .OrderBy(> f.Position)
                                 .Select(> f.Position)
                                 .ToList();

FeatureService.SortList(features, modifiedOrder, sortedPositions);
db.SubmitChanges();
return new EmptyResult();
}

private IEnumerable GetModifiedArrayIndexes(IEnumerable positions)
{
foreach (var position in positions)
yield return Convert.ToInt32(position.Substring(position.IndexOf(‘_’) + 1));
}

public static class FeatureService
{
public static void SortList(ICollection features, IList modifiedOrder, IList originalPositions)
{
for (var i = 0; i < features.Count; i++)         
{             
var feature = features.FirstOrDefault(> h.Id == modifiedOrder[i]);
feature.Position = originalPositions[i];
}
}
}

this method will save the positions of the list item as and when we change the sort order, that’s it we have successfully implemented the sortable list.

download the source code

jQuery collapsible menu

I was trying to implement a collapsible menu using jQuery following John Resig’s  online tutorial. it was great, such a nice effect with little code, I found one problem with the effect though, when I tried to click on the menu item which was already open it animated the list items again, I searched for any fixes for this but was not able to fin one so I thought let me try to fix this, here is the JavaScript fix for that

JavaScript

$(function() {

    $(“dd:not(:first)”).hide();

    $(“dt a”).click(function() {

        var curr_dd = $(this).parent().next();

        if (curr_dd.css(“display”) != “none”)

            return;

 

        $(“dd:visible”).slideUp(“slow”);

        curr_dd.slideDown(“slow”);

        return false;

    });

});

HTML

<dl>

            <dt><a href=”#”>Menu 1</a></dt>

            <dd>

                <ul>

                    <li>List Item 1</li>

                    <li>List Item 2</li>

                    <li>List Item 3</li>

                </ul>

            </dd>

            <dt><a href=”#”>Menu 2</a></dt>

            <dd>

                <ul>

                    <li>List Item 1</li>

                    <li>List Item 2</li>

                    <li>List Item 3</li>

                </ul>

            </dd>

            <dt><a href=”#”>Menu 3</a></dt>

            <dd>

                <ul>

                    <li>List Item 1</li>

                    <li>List Item 2</li>

                    <li>List Item 3</li>

                </ul>

            </dd>

            <dt><a href=”#”>Menu 4</a></dt>

            <dd>

                <ul>

                    <li>List Item 1</li>

                    <li>List Item 2</li>

                    <li>List Item 3</li>

                </ul>

            </dd>

        </dl>

Anonymous Types

Anonymous Types are inline class definition which is created at compile time, we use the same syntax of Object Initializer to declare a Anonymous Types but with out the class name

var customer = new {Name = “Paolo Accorti”, Country = “Italy”};

In my previous post about Local Type Inference we discussed about the varkeyword and how it provides us a relaxed way of declaring variable but in the case of Anonymous Types the usage of the varkeyword is a must to assign it to a variable. Anonymous Types is a very handy tool when when we handle data using LINQ

var employeeBirthDates = db.Employees
     .Select(=> new {e.FirstName, e.LastName, e.BirthDate});

var employeePhoneNumbers = db.Employees
     .Select(=> new {e.FirstName, e.LastName, e.HomePhone});

In the above scenario, it would have been difficult for us to declare each type and change them when we change the shape of the query result, Anonymous Types handles this efficiently, a few important things to know about Anonymous Types are as following

Anonymous Types can only have Read Only Properties as their members, noMethods can be associated with them, in the above example assigning a property would be illegal

foreach (var birthDate in employeeBirthDates)
    birthDate.BirthDate = DateTime.Now; // Error, cannot assign read only property

The Order and the Name of the Properties determine the type signature of the Anonymous Type, for example

var employee1 = new { FirstName = “Nancy”, LastName = “Davolio” };
var employee2 = new { FirstName = “Andrew”, LastName = “Fuller” };
var employee3 = new { LastName = “Leverling”, FirstName = “Janet” };
 
Console.WriteLine(employee1.GetType().Name);
Console.WriteLine(employee2.GetType().Name);
Console.WriteLine(employee3.GetType().Name);
Output:
<>f__AnonymousType0`2
<>f__AnonymousType0`2
<>f__AnonymousType1`2

we see that employee1 and employee2 are of the same type but employee3 is of a different type because of the order of the properties

Local Type Inference – var keyword

Type Inference is one of the important features for a dynamic language; it preserves type safety while allowing you to write code with more ease. The compiler has the built-in intelligence to determine the “Type” of a variable. 
There is always an argument about code readability when it comes to dynamic type inference, but when we work with external APIs and language features like LINK this becomes very handy tool, and it helps us to keep up with the design principle “Program to an Interface, not an implementation” 
The keyword “var” is used to denote the complier that you are declaring a dynamic type inference variable.

var i = 0;
is equivalent to
int i = 0;

The var keyword should not be mistaken with the VB6 Variant keyword or the .netObject keyword, C# is highly type safe, when the compiler converts the code into MSIL var is replaced with the real type, to prove this try running the code mentioned below

using System;
class Program
{
    public static void Main()
    {
        var i = 0;
        var assemblies = AppDomain.CurrentDomain.GetAssemblies();
 
        Console.WriteLine(i.GetType().Name);
        Console.WriteLine(assemblies.GetType().Name);
    }
}
 
Output:
Int32
Assembly[]

We should name our variables meaningfully when we use the var keyword or else the readability of the code will be affected in a very bad way

Valid Usage

we can assign constants, expression and methods with return type other than void to a variable declared with the var keyword, the var key word can be used only within a local scope, these are some valid usage

var x = 1;
var y = x;
var r = x % y;
var s = “Hello World”;
var l = s.Length;
var b = default(bool);

Invalid Usage

  • The cannot be used to declare a class level variable
  • It cannot be used as a return type for a method
  • It cannot be used to define the type of a method parameter
  • It cannot be used without assigning a value to the variable
  • It cannot be used if you assign null to a variable
class MyClass
{
    var k = 0; // cannot be used to declare a class level variable
 
    public void MyMethod( var x ) {} // invalid parameter type
 
    public var Mymethod() {return false;} // invalid return type
 
    public void MyMethod()
    {
        var x; // Syntax error, ‘=’ expected
        var y = null; // Cannot infer local variable type from ‘null’
    }
}

LINQ: Introduction

What is LINQ 

LINQ is a uniform programming model for any kind of data. LINQ enables you to query and manipulate data with a consistent model that is independent from data sources.

LINQ stands for Language Integrated Query

LINQ can be used to query against any kind of data collection like Database, XML file, ADS and so on, technically speaking any class that implements the IEnumerable or IQueryable interface to know about the difference between these two interfaces kindly visit my post

currently LINQ comes in different flavors like 

  • LINQ to Objects
  • LINQ to ADO.NET
  • LINQ to XML
  • LINQ to Entities

LINQ is supported in both C# 3.0 and VB 9.0 (.NET 3.5 Framework)

To have a better understanding of LINQ you need have basic understanding on C# language features like 

Refactoring: Introduction

When we work on a project as a developer our main focus is to write code and complete the requirements of the modules given to us, once we are done we just call it a day, when the other developers try to refer the module we develop they are clueless most of the time and the worst part we ourselves forget what we did and what a particular line of code is supposed to do.

In  Agile software development we follow practices like Test Driven Development(TDD), Refactoring to address this kind of confusions, Refactoring is a disciplined technique for restructuring an existing body of code, meaning altering its internal structure without changing its external behavior. When we try to implement a functionality for the first time we are focused to achieve the result, that’s totally fine but if we spend a little more time following the guidelines of what TDD and Refactoring says we can save a lot of time in the future and we will be thinking about adding features instead of working on the bugs.

Red, Green, Refactor

TDD says that we should first write aUnit Test before implementing the functionality, this ensures that the method which we are about to implement returns the expected result, the more tests we write to cover all the conditions the method will run under the more stable the functionality. Another main benefit of this step is that in future when someone else modifies/enhances this method they wont be breaking the functionality, this is very important when we work as a team and the project undergoes change in a rapid pace.

When we write this test first it is going to break obviously since there is no method to back up the test but we should not consider this step as a trivial one because this test drives a lot of attributes about the method we are about to write, right from the name to the signature and the return type. The failed test gives us the Red alarm and there our goal should be turning that into Green, that where we go crazy and write lines and lines of code and implement the functionality and pass make the test Pass.

Now  comes the important step,Refactoring the code, we have to covert the code we wrote from a complex block of language syntax to a simpler form, reading the code should be like reading a story, the time we allocate is for this process is definitely well spent, it saves lot of our time in the future. This is not the only time we should consider refactoring the code, generally when there is a feeling that we are complicating things we should consider Refactoring the code, these signals are called “code smells”, code smells indicates when to Refactor, some of the common code smells are

  • Non Meaningful Names
  • Duplicate Code
  • Long Methods
  • Large Classes
  • Long Parameter Lists
  • Multi location code changes

Performance?

One question that is asked often about Refactoring is that whether it will improve performance or not, Refactoring is not a step which considers to improve performance but refactoring helps us to do that indirectly, it improves software quality, it makes maintenance easy so it makes performance optimizations easier and ensures that the we are not breaking the system when we do performance optimizations.

Sample Refactoring

Before:

public int Product (int n1, int n2)
{
    int p;
    p = n1 * n2;
    return p;
}

After:

public int Product (int number1, int number2)
{
    return number1 * number2;
}
Video