views:

31

answers:

1

Is there any to return what rank in a list something is in during a sort using jquery? Essentially, I want to do what thousands of others are doing (and I've searched thoroughly on stackoverflow) and have a database update from a sortable.

Each item in the database has a "Position" property - initially set to 0. The ul is populated and drawn out, and I want to route back to the controller when it is updated and store their positions in the list.

I am using ASP.NET MVC/C# as my code base - but I am having trouble finding full examples of this.

A: 

Hah! I figured it out. I'm posting it here for everyone to enjoy.

$("ul#unorderedListIdGoesHere li").index(ui.item);


<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Models.Section>>" %>

    <ul id="sections">
    <% foreach (var item in Model) { %>
    <li class="ui-state-default" id="<%= item.Id %>">
        <span class="ui-icon ui-icon-arrowthick-2-n-s"></span><%= Html.Encode(item.Name) %>
    </li>
    <% } %>
    </ul>

<script type="text/javascript">
    $(document).ready(function() {
    $("#sections").sortable({
    update: function(event, ui) {
            $("ul#sections li").each(function(){
                var position = $("ul#sections li").index(this);
                var section = $(this).attr("id");
                $.post("/Sections/Position", { position: position, section: section });
                })
            }
        }).disableSelection();
    });
</script>
<style type="text/css">
    #sections { list-style-type: none; margin: 0; padding: 0; width: 60%; }
    #sections li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.4em; height: 18px; }
    #sections li span { position: absolute; margin-left: -1.3em; }
</style>
Stacey