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: 24482

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

Allen Michaels 12/17/2014 4:37 PM
In response to Cascading DropDownLists with jQuery and ASP.NET
Fantastic thank you so much!...

Emily 12/17/2014 12:36 PM
In response to Parameterized IN clauses with ADO.NET and LINQ
Thanks, very helpful!!!! Can i use this for multiple in's ????? IN (.....) and IN(...) and IN...

sss 12/16/2014 3:06 PM
In response to Solving the Operation Must Use An Updateable Query error
good...

Gjuro 12/15/2014 10:30 PM
In response to Examining the Edit Methods and Edit View
You have one fromr (and it should be from, I suppose). :-)...

Gjuro 12/15/2014 10:27 PM
In response to Adding Search
Hi, thnx for all this C#->VB translations. Yet, the following code block is (slightly) in error it a...

Scot 12/14/2014 1:39 PM
In response to Entity Framework 6 Recipe - Alphabetical Paging In ASP.NET MVC
Thanks,Mike I found solution....

Gjuro 12/13/2014 10:52 PM
In response to Accessing Your Model's Data from a Controller
The article mentions "Creating an Entity Framework Data Model for an ASP.NET MVC Application" (at is...

Samuel 12/13/2014 8:40 AM
In response to Displaying The First n Characters Of Text
I have failed to use the extension because it throws an error that it doesn't recognise the chop be...

Ignas 12/12/2014 5:11 PM
In response to Cleaner Conditional HTML Attributes In Razor Web Pages
Any suggestions for Html Helper elements with HtmlAttributes, when you need to conditionally set it...

Gautam 12/11/2014 8:50 PM
In response to Validation In Razor Web Pages 2
Hi Mike Is this required for V3, non html helper input...