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

0 Comments

Recent Comments

Gayan 7/3/2015 6:20 AM
In response to 7 C# 6.0 Features That Every ASP.NET Developer Should Know About
Great Article thanks...

Semil 7/1/2015 7:03 AM
In response to iTextSharp - Drawing shapes and Graphics
I have created a rectangle using above methode. Now I want to add a text in the center of this How I...

Satyabrata Mohapatra 6/30/2015 6:12 PM
In response to Reading Excel Files Without Saving To Disk In ASP.NET
Ahh.....this is awesome. Happy to see after a long time you wrote a article on web form :D...

Marty 6/30/2015 7:16 AM
In response to Posting Data With jQuery AJAX In ASP.NET Razor Web Pages
Mike, you're the Man! Another great article. So incredibly helpful. I'm definitely going to buy your...

Rohan 6/30/2015 5:32 AM
In response to ASP.NET MVC 5 with EF 6 - Working With Files
Very good and helpful tutorial. Thanks. Just wanted to know what would be the max file size limit we...

Fernando 6/30/2015 1:59 AM
In response to Programmatically accessing data from DataSource controls
What if I want to pass parameters natively using the DataSourceSelectArguments object, instead of be...

pankaj 6/29/2015 3:13 PM
In response to How to retain carriage returns or line breaks in an ASP.NET web page
very nice i'm use this in my code thank you.... ...

Mike 6/29/2015 2:22 AM
In response to MVC 5 with EF 6 in Visual Basic - Sorting, Filtering and Paging
This is the first example that I have found that works....

Marty 6/28/2015 4:57 AM
In response to Posting Data With jQuery AJAX In ASP.NET Razor Web Pages
Mike, what if I don't want to render back the text to the browser, but I want to send it some other...

Mike 6/27/2015 4:00 PM
In response to Migrating Classic ASP To ASP.NET Razor Web Pages Part One- Razor Syntax And Visual Basic
have you used any of the code converters to convert classic asp to c#? If so, which one do you have...