Site Meter
 
 

Drag-and-drop sorting for our ASP.NET MVC list editor (in one line of code)

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>

15 Responses to Drag-and-drop sorting for our ASP.NET MVC list editor (in one line of code)

  1. Pingback: Dew Drop - January 1, 2009 | Alvin Ashcraft's Morning Dew

  2. Simon,

    I think it would be useful for you to elaborate on the Model Binding functionality in this context.

    I am doing some drag/drop sorting in a site of mine but am manually composing the request data for the json call to my action. It sounds like there may be an easier way from what you mention briefly in this post.

    Thanks,
    Steve.

  3. Wookie

    I am also saving the sort automatically, via JSON, but then lots of JSON calls were being sent to the server, because sorting is usually a multi-step operation.

    So what I do now is to wait for an arbitrary idle time (say, 7 seconds) after the last sorting event happened, then I send a request with the new sort order.

  4. Steve

    @Steve Burman: Sorry if it wasn’t clear – this post is a follow-up to a previous post in which I explained the mechanism in more detail. See http://blog.codeville.net/2008/12/22/editing-a-variable-length-list-of-items-in-aspnet-mvc/, or download and inspect the source code to learn more about how it works.

    @Steve Burman, @Wookie: I guess the difference is that you’re saving the updated sort order in real time every time the user makes a change, whereas in my example I want to wait until the user clicks a “Save” button, then I submit and deal with the whole form at once.

    Both approaches are valid! One benefit of mine is that there’s a clear “unit of work” (i.e., all the items added, deleted, edited, and reordered) which can be sent to the model tier to be validated and processed as a single batch. It also minimises the amount of JavaScript needed, because ultimately it’s just a traditional HTML form submission.

  5. Pingback: Reflective Perspective - Chris Alcock » The Morning Brew #256

  6. markd

    Works well in IE, but I’m getting some pretty odd behaviour using FF 3.0.3 – is this a known limitation?

    specifically values are not persisting between UI operations (sorting / add / delete)

    Looks really good though… looking forward to the book

  7. Steve

    @markd – oh yes, I forgot to mention – there’s a bug in ASP.NET MVC Beta Ajax libraries which causes input controls state to be lost after insertion operations. I reported this to the MVC team a while back at http://www.codeplex.com/aspnet/WorkItem/View.aspx?WorkItemId=2893 I’m hoping they’ll fix this in time for the RTM release.

    If this issue affects you, please visit that link and vote for it to be fixed.

  8. Hey Steve,

    I tried it for myself and got a Server Error?

    The infamous “Object reference not set to an instance of an object” no less …

  9. Steve

    Hello Mr Mitchell!

    Thanks for letting me know. It seems my dodgy web host thought it would be OK to change some files on the server without asking me. This is now fixed. Try it again!

  10. Alexander

    Ignore the above, looks like your link and my link both include a “,” so much for trying to be grammatically correct =)

  11. Roy

    Hey Steve,

    The param (IList gifts) to SaveGifts is going in as null when you click save changes.
    BTW i used the source code from the following link

    http://blog.stevensanderson.com/blogfiles/2009/January/SortableEditListDemo.zip

    Am i missing something??

    Thanks,
    Roy

  12. Pollito

    Do you have a VS 2010 solution? I am getting all kinds of errors after converting to 2010.

  13. sarath revuri

    the code is not working in ie 9 does any one have a fix for that?

  14. karnav

    Do u have the code to work without MVC.