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.

Published Jan 1, 2009

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:

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:

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!
</p>

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

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

Update: This post was originally written for ASP.NET MVC 1.0 Beta. I’ve written a newer version of this post that applies to ASP.NET MVC 2.0 (Release Candidate). Note that this technique doesn’t actually work quite so easily with the final version of ASP.NET MVC 1.0, because its model binding convention changed in a way that means you have to massage the data into a numerical sequence for it to work. See comment #25 for a hint about one way to do this, or upgrade to ASP.NET MVC 2.0.