Search code examples
c#asp.net-mvcjquery-ui-sortabledraggable

Sortable, draggable, orderable table + mvc not updating order correctly


I'm trying to add an orderable table to my view. The sorting works when doing it in the View New.cshtml. It uses jQuerys sortable. If I add some instructions (1-5 in this case) I can move them around thanks to the sortable script. But when I try to add a new instruction after the reordering, the order change from:

enter image description here

to

enter image description here

I guess it has something to do with the hidden form

@Html.HiddenFor(m => m.Recipe.Instructions[i].Number, new { @id = "Number"})

It needs to update its value when I reorder the fields in the sortable table.

What am I missing here?

RecipeController.cs

public ActionResult Create(NewRecipeViewModel viewModel, string command)
{

//...more code...

    var instructionList = new List<Instruction>();

    if (viewModel.Recipe.Instructions != null)
    {
        for (int i = 0; i < viewModel.Recipe.Instructions.Count; i++)
        {
            var instruction = new Instruction
            {
                Id = viewModel.Recipe.Instructions[i].Id,
                Name = viewModel.Recipe.Instructions[i].Name,
                Number = viewModel.Recipe.Instructions[i].Number

            };
            instructionList.Add(instruction);
        }
    }

    if (command.Equals("AddInstruction"))
    {
        var instruction = new Instruction
        {
            Name = viewModel.NewInstruction.Name,
            Number = viewModel.Recipe.Instructions.Count + 1
        };

        recipe.Instructions.Add(instruction);
        viewModel.Recipe = recipe;

        return View("New", viewModel);
    }

//...more code...
}

New.cshtml

<div class="form-group" style="margin-top: 170px;">
    <label class="col-md-2 control-label">
        Lägg till instruktion:
    </label>
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.NewInstruction.Name, new { @class = "form-control" })
    </div>
</div>
<div class="form-group" style="margin-top: 300px;">
    <label class="col-md-2 control-label">
    </label>
    <div class="col-md-10">
        <button type="submit" name="command" value="AddInstruction" class="btn btn-primary">Add instruction</button>
    </div>
</div>
<div class="form-group" style="margin-top: 100px;">

    <label class="col-md-2 control-label">
        Instructions:
    </label>
    <div class="col-md-10">
        <table class="table table-bordered table-hover pagin-table" style="margin-top: 10px">
            <thead>
                <tr bgcolor="#f5f5f5">
                    <th>Order:</th>
                    <th>Instruction:</th>
                </tr>
            </thead>
            <tbody id="sortable">
                @if (Model.Recipe.Instructions != null)
                {
                    for (int i = 0; i < Model.Recipe.Instructions.Count; i++)
                    {
                        <tr>
                            @Html.HiddenFor(m => Model.Recipe.Instructions[i].Id)
                            <td class="order">
                                @Model.Recipe.Instructions[i].Number
                                @Html.HiddenFor(m => m.Recipe.Instructions[i].Number, new { @id = "Number"})
                            </td>
                            <td>
                                @Model.Recipe.Instructions[i].Name
                                @Html.HiddenFor(m => m.Recipe.Instructions[i].Name)
                            </td>
                        </tr>
                    }
                }
            </tbody>
        </table>
    </div>
</div>
 <script type="text/javascript">
     $(document).ready(function() {
             $('#sortable').sortable({
                 update : function(event, ui) { 
                     $('td.order').each(function(index) {
                        var order = index + 1;
                        $(this).find('span').text(order);
                        $(this).find('.Number').val(order);
                     });
                 }
             });
     });
 </script

EDIT: Added

instructionList.Sort((s1, s2) => s1.Number.CompareTo(s2.Number));

to RecipeController.cs. The rest is credit to Stephen Muecke.

RecipeController.cs

public ActionResult Create(NewRecipeViewModel viewModel, string command)
{

//...more code...

    var instructionList = new List<Instruction>();

    if (viewModel.Recipe.Instructions != null)
    {
        for (int i = 0; i < viewModel.Recipe.Instructions.Count; i++)
        {
            var instruction = new Instruction
            {
                Id = viewModel.Recipe.Instructions[i].Id,
                Name = viewModel.Recipe.Instructions[i].Name,
                Number = viewModel.Recipe.Instructions[i].Number

            };
            instructionList.Add(instruction);
        }
        instructionList.Sort((s1, s2) => s1.Number.CompareTo(s2.Number));
    }

//...more code...
}

New.cshtml

 @* More code *@
 <td class="order">
      <span>@Model.Recipe.Instructions[i].Number</span>
      @Html.HiddenFor(m => m.Recipe.Instructions[i].Number, new {@class = "Number"})
 </td>

 @* More code *@    

 <script type="text/javascript">
     $(document).ready(function() {
             $('#sortable').sortable({
                 update : function(event, ui) { 
                     $('td.order').each(function(index) {
                        var order = index + 1;
                        $(this).find('span').text(order);
                        $(this).find('.Number').val(order);
                     });
                 }
             });
     });
 </script

Solution

  • Your selector in the update function is incorrect and would return undefined (you are missing the # (id selector) and in anycase the $ creates a jQuery object, so it would be .val(...), not value=....

    However using $('#Number').val(index + 1) will not work correctly since it would only ever update the first element with id="Number". Duplicateid` attributes are invalid html.

    Use a class name and relative selectors instead. Change the html to

    <td class="order">
        <span>@Model.Recipe.Instructions[i].Number</span>
        @Html.HiddenFor(m => m.Recipe.Instructions[i].Number, new { @class = "Number"})
    </td>
    

    and then the script to

    $('#sortable').sortable({
        update : function(event, ui) { 
            $('td.order').each(function(index) {
                var order = index + 1;
                $(this).find('span').text(order );
                $(this).find('.Number').val(order );
            });
        }
    });