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:
Last Updated:
Posted by:
Total Views to date: 27817

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 I end up deleting quite a lot. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Requests to fix your code (post a question to forums.asp.net instead, please)
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam

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

hosein ey 2/25/2015 1:56 PM
In response to ASP.NET MVC 5 with EF 6 - Working With Files
tnx for this article do you think next version of entityframework support's the sql server and ?...

Saywer Ford 2/25/2015 5:15 AM
In response to Optimising ASP.NET Web Pages Sites - Bundling And Minification
Great Article. I did everything right and working fine. How about page specific js files. Lets I...

Saravanan 2/24/2015 10:54 AM
In response to Optimising ASP.NET Web Pages Sites - Bundling And Minification
Hi, Great article about the Bundling and minification. Regards the caching as you mentioned the...

Justin 2/24/2015 10:43 AM
In response to Scheduled Tasks In ASP.NET With Quartz.Net
I'm having the same problem as Ingmar. Everything is working fine locally in Visual Studio, but I it...

Logan Mudlo 2/23/2015 4:59 PM
In response to WebMatrix - A First Application
Is there a way to prevent the automatic close on a Database.Open() call?...

Mog0 2/23/2015 11:16 AM
In response to ASP.NET MVC 5 with EF 6 - Working With Files
Probably a silly question but why did you disable cascade delete and implement it yourself?...

Jose-Maria 2/19/2015 3:29 PM
In response to Migrating From Razor Web Pages To ASP.NET MVC 5 - Views and Controllers
Just great ! Many thanks Mike....

Satyabrata Mohapatra 2/19/2015 12:02 PM
In response to Migrating From Razor Web Pages To ASP.NET MVC 5 - Views and Controllers
This is great!!...

Ryan Helmoski 2/19/2015 10:24 AM
In response to Conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value
Thank you!...

Harsha 2/19/2015 8:27 AM
In response to iTextSharp - Adding Text with Chunks, Phrases and Paragraphs
Hi, Can text area be created so that I can type text in the area in pdf document? We have Add text...