So you can use ASP.NET MVC’s model binding conventions to implement a list editor where the user can dynamically add and remove items. Great! But how can you let the user control the order of the items? For example, when editing a list of actors in movie, the user might want to move the most famous actor up to the top of the list.

The natural UI metaphor here is drag-and-drop (not any nasty little “move up/down” arrows). To try the desired behavior for yourself, check out the following updated live demo:

Try it yourself (launch live demo) Download the source code

Implementation

Drag-and-drop used to be difficult, because every browser exposes a different API for it, but fortunately the jQuery UI project makes it much easier. What really surprised and delighted me is that jQuery UI’s Sortable component is so neatly compatible with the dynamic list editor from my previous blog post that we can implement the whole sorting business in just one single line of code!

Starting from the list editor demo from the previous blog post, all I needed to add was the following:

<script type="text/javascript">
    $(function() {
        $("#items").sortable({axis: "y"});
    });
</script>

This tells jQuery UI to get the elements inside the <div> with ID “items”, and make them sortable relative to one another. When the MVC Framework’s model binding facility later parses the incoming data to a collection, your action method will receive the data items in whatever order the user has sorted them. Job done!

Of course, to make this work, you also need to reference jQuery and jQuery UI, as follows:

  1. Go to the jQuery UI website and download a personalized version that includes the Sortable component. Put this in your ASP.NET MVC application’s /Scripts folder
  2. In your master page’s <head> section, reference both jQuery and your jQuery UI file:
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/jquery-1.2.6.min.js") %>"></script> 
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/jquery-ui-personalized-1.6rc4.min.js") %>"></script>