如何 post 列表排序后的重新排列顺序?

How can I post the rearranged order of a list after it has been sorted?

问题举例:

我认为这是因为列表项是在页面加载时以固定顺序生成的,并且当 UI 更新时该顺序不会改变。有没有办法提交 SortOrderOptions 的更新列表?

项目列表:

<div class="row">
    <ul id="sortable" style="list-style: none; padding-left: 0px; width: 100%;">
        @for (var x = 0; x < Model.SortOrderOptions.Count; x++)
        {
            <li style="width: 100%;">
                <div class="row">
                    <div class="col-6" style="padding-left:30px;">
                        <label class="kt-checkbox kt-checkbox--brand"><input type="checkbox" asp-for="@Model.SortOrderOptions[x].SortBy" class="sortBox" /><span></span></label>
                        <label>@Model.SortOrderOptions[x].Name</label>
                        <input type="hidden" asp-for="@Model.SortOrderOptions[x].Name" value="@Model.SortOrderOptions[x].Name" />
                    </div>

                    <div class="col-3 center">
                        <label asp-for="@Model.SortOrderOptions[x].Subtotal">
                            <label class="kt-checkbox kt-checkbox--brand"><input type="checkbox" disabled="@(Model.SortOrderOptions[x].SortBy != true ? "disabled" : null)" asp-for="@Model.SortOrderOptions[x].Subtotal" class="subtotalBox" /><span></span></label>
                        </label>
                    </div>

                    <div class="col-3">
                        <label asp-for="@Model.SortOrderOptions[x].NewPage">
                            <label class="kt-checkbox kt-checkbox--brand"><input type="checkbox" disabled="@(Model.SortOrderOptions[x].SortBy != true ? "disabled" : null)" asp-for="@Model.SortOrderOptions[x].NewPage" class="newPageBox" /><span></span></label>
                        </label>
                    </div>
                </div>
            </li>
        }
    </ul>
</div>
<script src="~/libs/js/jquery.js"></script>
<script src="~/libs/jqueryui/jquery-ui.js"></script>

Javascript:

$("#sortable").sortable({
    axis: "y",
    containment: "parent"
});

$('#submit').off('click').on('click', function (evt) {
    var data = $('form').serialize();
    var url = "@Context.Request.Path.Value.Replace("/Test","", StringComparison.OrdinalIgnoreCase)";
    evt.preventDefault();
    //Ajax form post
    $.ajax({
        type: 'POST',
        data: data,
        contentType: dataType,
        url: '@Url.Action("PBSCSubmit","Reports")',
        beforeSend: function(){
            // Show loading spinner while processing
            $('#loader').modal({
                backdrop: 'static',
                keyboard: false
            });
        },
        success: function (data) {
            if (data.success) {
                //Success with warnings
                if (data.warning) {
                    $('#loader').modal('toggle');
                    //Toggle the error modal and display messages
                    $('#errorsModal').modal('toggle');
                    //Add <br> tags when there is a linebreak in the string.  This will add the line breaks into the HTML.
                    $('#errorsModal .modal-body p').html(data.message.replace(/(?:\r\n|\r|\n)/g, '<br>'));
                    //Open PDF on warning modal "OK" button click
                    $('#modalConfirm').on('click', function () {
                        window.open(url + "/ShowPDF?path=" + data.pdf, "_blank");
                    });
                } else {
                    //Success without warnings
                    $('#loader').modal('toggle');
                    window.open(url + "/ShowPDF?path=" + data.pdf, "_blank");
                    if (data.csvCreated) {
                        window.open(url + "/DownloadFile?path=" + data.csv + "&fileName=" + CSVFileName, "_blank");
                    }
                }
            } else {
                $('#loader').modal('toggle');
                //Toggle the error modal and display messages
                $('#errorsModal').modal('toggle');
                //Add <br> tags when there is a linebreak in the string.  This will add the line breaks into the HTML.
                $('#errorsModal .modal-body p').html(data.message.replace(/(?:\r\n|\r|\n)/g, '<br>'));
            }
        },
        error: function (jqXHR) {
            $('#loader').modal('toggle');
            handleAjaxError(jqXHR);
        }
    });
});

控制器:

public IActionResult PBSCSubmit(PaymentsBySelectionCriteria report)
{
    var convertedReport = new PaymentsBySelectionCriteria().ConvertToCriteria(report);
    convertedReport.PathToProjectFile = reportPath;
    var path = Path.GetDirectoryName(env.WebRootPath) + "\pdfs\" + Guid.NewGuid() + ".pdf";
    var csvPath = Path.GetDirectoryName(env.WebRootPath) + "\csvs\" + Guid.NewGuid() + ".csv";
    var reportModel = new ReportPaymentsBySelection();

    if (convertedReport.CreateCSVFile == true)
    {
        convertedReport.CSVFileName = csvPath;
    }

    reportModel.CreateReportAsPDFOrAddToQueue(convertedReport, path, loggedInUserID, out Notification notification, out bool addedToQueue);

    //Add the report to the process queue
    if (addedToQueue == true)
    {
        return Json(new
        {
            success = false,
            message = "The report has been added to the queue."
        });
    }

    if (notification.HasErrors)
    {
        return Json(new
        {
            success = false,
            message = notification.GetConcatenatedErrorMessage(Environment.NewLine + Environment.NewLine)
        });
    }

    return Json(new
    {
        success = true,
        warning = notification.HasWarnings,
        message = notification.GetConcatenatedWarningMessage(Environment.NewLine + Environment.NewLine),
        pdf = path,
        csvCreated = convertedReport.CreateCSVFile,
        csv = csvPath
    });
}

您可以使用 Html Table

的一种方法来完成此操作
  1. 在 table
  2. 中创建相同的东西
  3. 然后允许用户拖放列表
  4. 最终将 table 行作为包含 javascript
  5. 的列表

以上列表将以用户排列的方式,我将在下面添加示例代码 您可以根据自己的意愿对列表进行排序,然后单击 'ClickMe' 按钮

此代码仅供您参考,与您的代码不同

<!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Easy Drag and Drop HTML Table Rows With jQuery</title>
        <!-- Bootstrap core CSS -->
        <link href="https://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
        <!-- Custom styles for this template -->
        <link href="https://getbootstrap.com/docs/4.0/examples/starter-template/starter-template.css" rel="stylesheet">
      </head>
     
      <body>
     
        <main role="main" class="container">
     
         <table class="table table-striped table-hover" id="tbl">
            <thead class="thead-dark">
                <tr>
                    <th>Row</th>
                    <th>Name</th>
                    <th>ID Number</th>
                    <th>Location</th>
                    <th>Date</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                  <td>01</td>
                  <td>Rahim Hawkins</td>
                  <td>1640060874099</td>
                  <td>Bursa</td>
                  <td>May 29, 2017</td>
                </tr>
                <tr>
                  <td>02</td>
                  <td>Carter James</td>
                  <td>1672062705399</td>
                  <td>Geer</td>
                  <td>Mar 30, 2019</td>
                </tr>
                <tr>
                  <td>03</td>
                  <td>Merritt Fernandez</td>
                  <td>1669120981299</td>
                  <td>Gooik</td>
                  <td>Jun 3, 2017</td>
                </tr>
                <tr>
                  <td>04</td>
                  <td>Ross Robbins</td>
                  <td>1640092139299</td>
                  <td>Lint</td>
                  <td>Mar 22, 2018</td>
                </tr>
                <tr>
                  <td>05</td>
                  <td>Allistair Warren</td>
                  <td>1690102625999</td>
                  <td>Bicester</td>
                  <td>Dec 22, 2017</td>
                </tr>
                <tr>
                  <td>06</td>
                  <td>Yoshio Finch</td>
                  <td>1643051322099</td>
                  <td>Baulers</td>
                  <td>Sep 15, 2018</td>
                </tr>
                <tr>
                  <td>07</td>
                  <td>Wylie Holland</td>
                  <td>1662122249099</td>
                  <td>Penicuik</td>
                  <td>Apr 22, 2018</td>
                </tr>
                <tr>
                  <td>08</td>
                  <td>Maxwell Lindsay</td>
                  <td>1637021237499</td>
                  <td>St. John's</td>
                  <td>Nov 30, 2018</td>
                </tr>
                <tr>
                  <td>09</td>
                  <td>Orson Schneider</td>
                  <td>1610061567599</td>
                  <td>Gresham</td>
                  <td>Mar 7, 2018</td>
                </tr>
                <tr>
                  <td>10</td>
                  <td>Ahmed Puckett</td>
                  <td>1626021923499</td>
                  <td>Valbrevenna</td>
                  <td>Jul 20, 2018</td>
                </tr>
            </tbody>
        </table>
       <button onclick="fun()">ClickMe</button>
        </main><!-- /.container -->
     
        <!-- Bootstrap & Core Scripts -->
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
        <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script> 
        <script src="https://getbootstrap.com/dist/js/bootstrap.min.js"></script>
     
        <script type="text/javascript">
          $('tbody').sortable();
           function fun(){
           var table = document.getElementById("tbl");
           var noOfrows=table.rows.length;
           var res = new Array(noOfrows);
           for (var i=0;i<noOfrows;i++){
           res[i]=table.rows[i].cells[0].innerHTML;
           }
           alert(res);
          }
        </script>
    
     
      </body>
    </html>

我为此想出了自己的解决方案,方法是创建一个新的 属性 来跟踪索引。我创建了一些隐藏的输入并为每个输入添加了 class sort-index

public class SortOrder
{
    public string Name { get; set; }
    public bool SortBy { get; set; }
    public bool Subtotal { get; set; }
    public bool NewPage { get; set; }
    public int SortIndex { get; set; }
}

单击提交按钮后,我将 re-order 的隐藏索引输入更新到 UI 中的当前位置。

//Update the SortIndex value of each sort order option
$(".sort-index").each(function (i, el) {
    //console.log("Index: " + i + ". Value: " + $(this).val());
    //Set the value of the sort index input to the index
    $(this).val(i);
});