Reputation: 21
I've got an MVC 3 application with a requirement for the Sysytem Admin to be able to generate an ordered list of device attributes from a master list of attributes and save it as a specified configuration.
I've looked at the question and answers for the following - Implementing Drag n Drop using JQuery
I've included the JQuery UI sortable libraries, scripts and styles to the View and visually everything seems to work great. Ityems are dragged and dropped fromthe master to the output list.
My problem is in retrieving the data from the output list - sortable JQuery UI element. In the referenced article, they recommend using the serialize method on the sortable element. However, sortable only appears to return the query string for the input elements on the form. The sortable element in my case is an ordered list and it's data isnot referenced.
How can I get the sortable element's data back to the controller?
Thanks.
Upvotes: 2
Views: 942
Reputation: 13141
jQuery UI's serialize method looks at the IDs of your elements and creates a serialized hash string that's suitable for posting back to your controller. By default, your IDs must be in one of the following formats:
<li id="setname=number"></li>
<li id="setname-number"></li>
<li id="setname_number"></li>
All of these will result in:
"setname[]=number&setname[]=number"
If the serialize method returns an empty string, then you are either not targeting the sortable elements correctly, they have not yet been initalized with the sortable() call, or the IDs are not in the correct format. Note that it is possible to modify the way jQuery UI serializes the elements by passing a custom 'key', 'attribute', and 'expression' parameters to the serialize method:
var sortedList = $('ul.sortableList').sortable('serialize', { attribute: 'itemid', key: 'foo[]', expression: /(.+)=(.+)/ });
Of course, you can always roll your own serialize method and pass the updated LI positions to your controller manually:
var positions = new Array();
$sortableLis.each(function () {
var sortableId = $(this).find('input[id$=SortableID]').val();
var sortOrder = $sortableLis.index($(this));
var SortablePosition = {
ID: encodeURIComponent(sortableId),
SortOrder: sortOrder
};
positions.push(SortablePosition);
});
$.ajax({
type: 'POST',
url: '/UpdateSortablePositions',
data: "{ positions: '" + $.toJSON(positions) + "' }",
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
Upvotes: 1