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)

Post to Twitter Post to Digg Post to Facebook

  • Scubago
    Can I see a live demo of this project?
  • 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.
blog comments powered by Disqus