23 March: Version 2.2.0 is now available on NuGet - READ ME

jQuery UI Helpers / Sortable

Simple Sortable

You can create a sortable widget with the BeginSortable method. This method returns a SortableBuilder object that is used to create the items by calling one of its BeginItem methods.

You should call the BeginSortable and BeginItem methods in a using statement. This is required to emit all the necessary HTML tags into the response.

The following example creates a simple sortable.

@using (var sb = Html.JQueryUI().BeginSortable())
{    
    using (sb.BeginItem())
    {
        <span>Item 1</span>
    }
    using (sb.BeginItem())
    {
        <span>Item 2</span>
    }
    using (sb.BeginItem())
    {
        <span>Item 3</span>
    }    
}

This is the result (you can reorder the items).

  • Item 1
  • Item 2
  • Item 3

The sortable creates a list. You can use CSS to change the appearance of the items.

@using (var sb = Html.JQueryUI().BeginSortable())
{
    for (int i = 0; i < 5; i++)
    {
        using (sb.BeginItem(new { @class = "sortable-item" }))
        {
            <span>Item @i</span>
        }
    }    
}

This creates the sortable below.

  • Item 0
  • Item 1
  • Item 2
  • Item 3
  • Item 4

Configuration

Like the other widgets the sortable also has a fluent configuration API. To use it, create the sortable with the Begin method which takes a Sortable as its argument. The following example demonstrates this.

@using (var sb = Html.JQueryUI().Begin(new Sortable().Placeholder("placeholder").Revert(true)))
{
    for (int i = 0; i < 5; i++)
    {
        using (sb.BeginItem(new { @class = "sortable-item" }))
        {
            <span>Item @i</span>
        }
    }    
}

The generated sortable is below.

  • Item 0
  • Item 1
  • Item 2
  • Item 3
  • Item 4

Sortable on Forms

You can put a sortable on a form and submit the order of the items. To do this you need to assign a name to the sortable and values to the items. Use the Name method and the appropriate overload of the BeginItem method. This creates hidden input elements to store the values.

@using (var sb = Html.JQueryUI().Begin(new Sortable().Name("ItemId")))
{
    for (int i = 0; i < 5; i++)
    {
        using (sb.BeginItem(i, new { @class = "sortable-item" }))
        {
        <span>Item @i</span>
        }
    }    
}

To receive the values on the server create an array parameter with the name you assigned to the sortable.

        [HttpPost]
        public ActionResult MyMethod(int[] itemId)
        {
            // ...
        }

And the working example:

  • Item 0
  • Item 1
  • Item 2
  • Item 3
  • Item 4

HTML Helpers

Fluent Configuration API