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

0 Comments

Recent Comments

Vijay 5/25/2015 2:12 PM
In response to How To Send Email In ASP.NET MVC
Thanks...

RR 5/25/2015 8:58 AM
In response to Web Pages - Efficient Paging Without The WebGrid
@MIke.. is it possible to combine pagination and filter (change category ) in the script? Thanks...

Irfan Khan 5/25/2015 6:19 AM
In response to Highlighting Keywords Found In Search Results
This is truely helpful. Thank you for the brilliant tip....

Manoj Kulkarni 5/25/2015 4:46 AM
In response to Custom TagHelpers in ASP.NET MVC 6
Thank you for nice article. Really helpful....

Sean 5/21/2015 4:20 AM
In response to ASP.NET MVC 5 with EF 6 - Working With Files
Thank you for the tutorial. Saving to the database works, but the save FilePath is not working. It...

KrASh 5/19/2015 11:10 PM
In response to Adding Search
Hello Mike, I have a question about the second search. In one line it has a where with the title and...

KrASh 5/19/2015 11:04 PM
In response to Accessing Your Model's Data from a Controller
Thanks, I had some silly mistake, can't remember now what it was (had some personal problems last i...

Satyabrata Mohapatra 5/18/2015 4:29 PM
In response to Error Handling in ASP.NET Razor Web Pages
Great article. Learned a lot....

Corstian Boerman 5/13/2015 12:59 PM
In response to ASP.NET 5 Middleware, Or Where Has My HttpModule Gone?
It looks as if this technique doesn't work anymore. (As of the VS 2015 RC release) When adding it...

Alvin 5/12/2015 1:20 PM
In response to Razor Web Pages E-Commerce - Adding A Shopping Cart To The Bakery Template Site
Maybe ability to update quantity of the items once you are in the "Review Cart" step. Also, if on...