Drag and Drop Categorized Item List with jQuery and ASP.NET MVC – Part 4

Controllers and AJAX

This is part 4 of a series. In this post I’ll go through the controller classes and how to use jQuery and AJAX to update the database with the position (or state) of where each section and item is moved to.

Every section can be dragged and dropped into any of the 4 columns and in any position within that column. This is the reason for both the ColumnNum and SortOrder fields of the Sections table described in part 2.

First we’ll dive into jQuery. Going back to our sortable() call for the sections, we need to add code that fires after an update event. The important thing to note here is that the update event will fire for both the column moving from and to. If moving within the same column, it’ll fire only once.

As set up in part 3, the column num is stored in the id attribute of the “listColumn” div, so with a little parsing we can retrieve the column who’s state just changed.

Next we’ll need the new order of the sections within each changed column. The sortable(“serialize”) call forms the section IDs into a “form/ajax submittable string” like this:

section[]=3&section[]=1&section[]=4

For more detail see the jQuery UI sortable page. Look under Methods > serialize.

Now we’ll do an AJAX post to a method within the section controller we’ll create below. Here’s the resulting jQuery:

function InitSectionSorting()
{
    $(".listColumn").sortable(
    {
        …,
        //update event fires both for column leaving and receiving
        update: function(event, ui)
        {
            //Extract column num from current div id
            var colNum = $(this).attr("id").replace(/col_/, "");

            $.post("/Section/UpdateSortOrder",
            { columnNum: colNum, sectionIdQueryString: $(this).sortable("serialize") });
        }
    });
}

In SectionController.cs, we’ll now code the UpdateSortOrder method to receive the serialized string from jQuery and pass it as a string array to it’s model class.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateSortOrder(int columnNum, string sectionIdQueryString)
{
    string[] separator = new string[2] { "section[]=", "&" };
    string[] sectionIdArray = sectionIdQueryString.Split(separator, StringSplitOptions.RemoveEmptyEntries);

    secRepo.UpdateSortOrder(columnNum, sectionIdArray);
    secRepo.Save();

    return Content("Success");
}

The return Content(“Success”) is simply to see that the update was successful using Firebug. You should see the text “Success” within Firebug’s Console tab after you drag and drop a section. It’s optional so you can remove it.

Now on to Items. They can be moved to any section and in any position, so the jQuery and controller code is almost the same Sections.

jQuery:

function InitItemSorting()
{
    $(".itemList").sortable(
    {
        ...,
        //update event fires both for item list leaving and receiving
        update: function(event, ui)
        {
            //Extract section id from parent section box
            var sectionId = $(this).closest(".secBox").attr("id").replace(/section_/, "");

            $.post("/Item/UpdateSortOrder",
                { sectionId: sectionId, itemIdQueryString: $(this).sortable("serialize") });
        }
    });
}

ItemController.cs:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateSortOrder(long sectionId, string itemIdQueryString)
{
    string[] separator = new string[2] { "item[]=", "&" };
    string[] itemIdArray = itemIdQueryString.Split(separator, StringSplitOptions.RemoveEmptyEntries);

    itemRepo.UpdateSortOrder(sectionId, itemIdArray);
    itemRepo.Save();

    return Content("Success");
}

In a later series we’ll cover editing the text of (and deleting) sections and items.

Download the source code (requires Visual Studio 2008 and ASP.NET MVC 1.0)

4 Responses to Drag and Drop Categorized Item List with jQuery and ASP.NET MVC – Part 4

  1. Scubago October 8, 2009 at 5:17 pm #

    Can I see a live demo of this project?

  2. pderksen October 9, 2009 at 9:20 am #

    Sorry. Right now I don't have a spare hosting plan to set this up. But you can download the source and run it locally in visual studio.

  3. Sasha September 10, 2010 at 1:57 am #

    i think that it should be better solution for getting array:

    string[] separator = new string[2] { “section[]=”, “&” };
    string[] sectionIdArray = sectionIdQueryString.Split(separator, StringSplitOptions.RemoveEmptyEntries);

    with php it was more elegant: http://www.webresourcesdepot.com/dynamic-dragn-drop-with-jquery-and-php/

    it already bring array from request.form

    i tried: int[], array and arraylist but without success :(

Trackbacks/Pingbacks

  1. ASP.NET MVC Archived Blog Posts, Page 1 - October 13, 2009

    [...] to VoteDrag and Drop Categorized Item List with jQuery and ASP.NET MVC – Part 4 (10/8/2009)Thursday, October 08, 2009 from Phil DerksenControllers and AJAX This is part 4 of a series. In this [...]

Leave a Reply