Saving jQuery Sortables In ASP.NET Razor Web Pages

jQuery Sortables offer a way to specify the order of a collection of items through an easy drag and drop interface. I have just been working on the next release of Web Pages CMS and am in the process of implementing Sortables for managing the display order of menu items. This article looks at how they can be used in Razor Web Pages and shows one way of saving the resulting order to a database.

All you really need to get going with Sortables is a reference to jQuery, and another to jQuery UI. Both libraries come as part of the Razor Web Pages templates that Visual Studio generates, but if you are working with WebMatrix, you can use Nuget to install the libraries as packages. Or you can simply reference CDN-hosted files like the ones managed by Microsoft (http://www.asp.net/ajaxlibrary/cdn.ashx) or Google (https://developers.google.com/speed/libraries/devguide).

Once you have done that, you add the sortable command to an element that contains a collection of HTML elements that you want to be able to sort. In the following example, the items that I want to become sortable are contained in a div with the id of sortable:

<script>
    $(function () {
        $('#sortable').sortable()
    });
</script>

<div id="sortable">
    @for(var i = 1; i <= 10; i++){
        <div class="list-item">
            @((char)(i + 64))
        </div>
     }
</div>

This code will render 10 divs, each with a letter of the alphabet, starting at 'A'. The containing div has been declared as sortable so you will be able to reorder items within the list using your mouse. This is really easy but serves no practical use. You really need a way to identify each item, obtain its position in the list and then to save that data to a database. You do this using the jQuery each method.

The jQuery each method accepts two parameters: index and value, or the index of the current item within its collection and a reference to the actual item. In this example, items are retrieved from a database. The table is simple - it has an Id column, a Text column and an integer column for storing the item's display order:

@{
    var db = Database.Open("Sortables");
    var commandText = "SELECT Id, Text FROM Items ORDER BY DisplayOrder";
    var items = db.Query(commandText);
}

The items are displayed like this:

<div class="container">
    <div class="row">
        <div class="col-md-4 alert-info" id="message">
           Drag items to reorder them.
        </div>
    </div>
    <div class="row">
        <div id="sortable" class="col-md-4">
            @foreach(var item in items){
                <div class="list-item" id="@item.Id">
                    @item.Text
                    <div class="index"></div>
                </div>
            }
        </div>
    </div>
    <div class="row">
       <div class="col-md-2">
           <button>Save Order</button>
        </div>
    </div>
</div>

More observant readers may notice the use of Twitter Bootstrap here. The collection of items are made 'sortable' via jQuery and a click event is added to the button:

<script>
    $(function () {
        $('#sortable').sortable();
        $('button').on('click', function(){
            var ids = [];
            $('.list-item').each(function (index, value) {
                var id = $(value).prop('id');
                ids.push(id);
            });
            $.post(
                '/UpdateOrder',
                { Ids: JSON.stringify(ids) },
                function (response) {
                    if ($('#message').hasClass('alert-info')) {
                        $('#message').text('Items re-ordered successfully.')
                                     .removeClass('alert-info')
                                     .addClass('alert-success');
                    } else {
                        $('#message').effect("highlight", {}, 2000);
                    }
                }
            );
        })
    });
</script>

A Javascript array called 'ids' is created which is used in the button click event to capture the id of each sortable item in the order in which they have been positioned by the user. This array is converted to JSON using the browser's JSON.stringify method and posted to a file called UpdateOrder.cshtml, and once that has done its job successfully, the instruction div at the top of the page is updated to let the user know that their reordering has been successful.

Here's the code for the UpdateOrder.cshtml file:

@{
    var json = Json.Decode(Request["Ids"]);
    object[] ids = json; 
    var db = Database.Open("Sortables");
    var commandText = "UPDATE Items SET DisplayOrder = @0 WHERE Id = @1";
    foreach(var id in ids){
        db.Execute(commandText, Array.FindIndex(ids, i => i == id), id);
    }
}

The code sets up a SQL statement that updates the display order of an item. The two values passed in to parameters are the display order and the id. One thng of interest to note is how the plain array posted via jQuery appears in the Request.Form collection. Each element in the array is actually sent as a separate name/value pair, with the name of the array plus the indexing brackets (Ids[]) being used as the identifier. Since all elements have the same name, it works in the same way as grouped checkboxes or a multi-select - the values arrive on the server as a comma-separated string. This is converted to a C# array using the string,Split method and then looped through. On each iteration, the index of the current item is located in the array, and that is saved as the DisplayPosition value.

 

Date Posted: Monday, October 28, 2013 8:04 PM
Last Updated:
Posted by: Mikesdotnetting
Total Views to date: 23035

0 Comments

Add your comment

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.

Recent Comments

Gautam 11/20/2014 8:01 AM
In response to I'm Writing A Book On WebMatrix
Hello Mike, I read your book, loved it! However, I have a few request/suggestions: 1) an example...

Bret Dev 11/19/2014 8:39 PM
In response to The Difference Between @Helpers and @Functions In WebMatrix
Excellent post! One concern - where can you place global @Functions code within an MVC project to Is...

Rob Farquharson 11/19/2014 4:28 PM
In response to iTextSharp - Links and Bookmarks
How can I place text at an absolute position on the page? Also, how can I rotate text?...

Andy 11/17/2014 8:08 PM
In response to MVC 5 with EF 6 in Visual Basic - Sorting, Filtering and Paging
Hello I'm testing your sorting instructions above. This is great and I was able to get it to work...

Gautam 11/17/2014 5:51 PM
In response to WebMatrix - Database Helpers for IN Clauses
Hi Mike, I am very new to programming: In the above example if I want to use a delete button the...

donramon 11/17/2014 3:22 PM
In response to Entity Framework 6 Recipe - Alphabetical Paging In ASP.NET MVC
Congratulations on your new website look and the excellent articles. Thank you!...

Gautam 11/17/2014 11:26 AM
In response to Looking At The WebMatrix WebGrid
Hi Mike, I add the jquery script at the end of my html file.. when ajax attribute is added to the be...

Chet Ripley 11/15/2014 6:57 PM
In response to Adding A New Field
It appears the command is case sensitive. I had the same issue as Cameron. When I changed the to it...

Alvin 11/14/2014 12:49 PM
In response to Razor Web Pages E-Commerce - Adding A Shopping Cart To The Bakery Template Site
Great article Mike! When do you plan to extend the bakery shopping cart beyond this point?...

Gautam 11/14/2014 10:16 AM
In response to Web Pages - Efficient Paging Without The WebGrid
to get the count can we use only the below sql, why to join category and author table var sql =...