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:
<a style="border-right: black 2px solid; padding-right: 0.5em; border-top: silver 2px solid; padding-left: 0.5em; padding-bottom: 0.5em; border-left: silver 2px solid; color: white; padding-top: 0.5em; border-bottom: black 2px solid; background-color: green" href="http://razor.codeville.net/listeditor_sortable/app.ashx/Home/EditList" target="_blank" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://razor.codeville.net']);window.open("http://razor.codeville.net/listeditor_sortable/app.ashx/Home/EditList","mywindow","menubar=0,resizable=1,width=700,height=350"); return false;'>Try it yourself (launch live demo) </a> | 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
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
-
In your master page’s section, reference both jQuery and your jQuery UI file:
</li>
</ol>
<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>