如何使用JQuery Sortable从数据库中获取数据并回传数据

问题描述:

我正在尝试创建一个菜单,该菜单允许用户将列表项重新排序为新顺序.列表数据是从数据库中提取的.我已经为菜单编写了jQuery可排序功能功能,但是,在用户重新排序列表之后,我正努力将数据按新顺序保存回模型.

I am attempting to create a menu that allows the user to re order the list items into a new order. The list data is pulled from a database. I've coded the jQuery sortable functionality feature for my menu however, I am struggling to then save the data in the new order back to model after the user has re ordered the list.

这是我的可排序代码,除带有var objmodel的行外,其他所有代码均有效.创建此变量后,它设法从数据库中获取一个空对象,并用新的随机播放功能值填充该空对象(检查指向图像的链接).我需要做的就是抓住用户单击的对象,然后用新的顺序填充该对象.

This is my code for the sortable, it all works except for the line with var objmodel. When this variable is created it manages to grab an empty object from the database and populate the empty object with the new shuffle function value (check link to image). What I need it to do is to grab the object that the user has clicked on to then populate that object with the new order.

我确实在控制器内部的方法中使用了断点,并且我注意到它是从数据库中获取数据,但是将字段分配为null会产生NullReferenceException错误.该方法的屏幕截图如下:

I did use break point to with my method inside the controller and I noticed that it is picking up the data from the database but assigning the fields to null which generate a NullReferenceException error. Screen shot of the method is below:

数据示例:

  1. cookie
  2. 饼干
  3. 巧克力

并且在用户重新订购后:

And after re-order by user:

  1. 巧克力
  2. 饼干
  3. cookies

我一直在努力解决这个问题,如果有人可以提供帮助,我会提供解决方案吗?

I have been struggling with this matter and will do with a solution if anyone can help?

 $(document).ready(function () {
    $('#MenuItem tbody').sortable({
        axis: 'y',
        update: function (event, ui) {
            alert(ui.item.context.id);
            var order = 1;
            var model = [];
            // var sortedIDs = $("#MenuItem tbody").sortable("serialize");
            //alert(sortedIDs);
            //alert(objModel);

            //$.getJSON('ProductsList', { ID: objModel }, function (result) {

            $("#MenuItem tbody tr").each(function () {

                var objModel = { Id: ui.item.data("model"), ShuffleFunction: order }; //This is for example to build your object and push in a modal array.

                //building a new object and pushing in modal array 
                //Here I am setting OrderNo property which is i am using in my db and building my object
                model.push(objModel);
                     order++;
                    //alert(result);
                //});
            });

           if (model.length > 1) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: '@Url.Action("MoveFunction", "Product")', //This is my url put your url here and pass model as data it is an array of my items
                    data: JSON.stringify({ model: model }),
                    success: function (data) {
                        //do something
                    },
                    error: function (e) {
                        //do something
                    }
                });
            }
        }
    });

});

 <table id = "MenuItem"  class="promo full-width alternate-rows" style="text-align: center;">  <!-- Cedric Kehi DEMO CHANGE -->




        <tr>
            <th>Product Code
            </th>
            <th>Product Template
            </th>
            @*<th>
                @Html.DisplayNameFor(model => model.IndexList[0].Priority)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.IndexList[0].WindowProduct)
            </th>*@
            <th>Description <!-- JACK EDIT -->
            </th>
            <th>Actions</th>
        </tr>
        <tbody >


        @foreach (var item in Model.IndexList)
        {




            <tr id ="trendingDisplay">

                <td class="center-text">

                    @Html.DisplayFor(modelItem => item.ProductCode)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.ProductTemplate.Description)
                </td>
                @*<td class="center-text">
                    @Html.DisplayFor(modelItem => item.Priority)
                </td>
                <td class="center-text">
                    @Html.Raw(item.WindowProduct ? "Yes" : "No")
                </td>*@
                <td>
                    @Html.DisplayFor(modelItem => item.Description)

                </td>



            </tr>



        }


            </tbody>

    </table>

 [HttpPost]
    // This Code Needs Fixing 
    public void MoveFunction(List<Product> model)
    {

        int id = (int)System.Web.HttpContext.Current.Session["CustomerID"];
        int customerid = (int)System.Web.HttpContext.Current.Session["CustomerID"];
        int promotionid = (int)System.Web.HttpContext.Current.Session["PromotionID"];

        List<Product> productList = new List<Product>();
        productList = ProductLogic.GetBy(x => x.PromotionID == promotionid && x.Active == true);
        int i = 1;

        foreach (var item in model)
        {
            var status = ProductLogic.GetBy(x => x.ProductID == item.ProductID).FirstOrDefault();
            if (status != null)
            {
                status.ShuffleFunction = item.ShuffleFunction;
            }
            ProductLogic.Update(status);
            i++;
        }

    }

我注释了以下行:

alert(ui.item.context.id);

我想你是说:

alert(ui.item.attr("id"));

或者:

alert(ui.item[0].context.id);

无论如何,这在我的测试中引起了问题.接下来,我必须查看您的循环并确定排序后要使用的信息.由于每个排序项都是一行,因此我找不到行的data-model属性;因此,我添加了一个.请考虑这是否是您的.NET脚本生成的HTML.由于这就是您的jQuery所使用的,因此在示例中不值得使用.NET脚本,而应在示例输出中使用某些类型.

Regardless, it was causing an issue in my testing. Next I had to look at your loop and determine what information you were trying to use after the sort. Since each sort item was a row, I could not find a data-model attribute for the rows; hence, I added one.Consider if this was the resulting HTML from your .NET Script. Since that's what your jQuery will be working with, it's not worth using .NET script in your example, but some type of example output.

工作示例: https://jsfiddle.net/Twisty/45dw9fve/3/

HTML

<table id="MenuItem" class="promo full-width alternate-rows" style="text-align: center;">
  <!-- Cedric Kehi DEMO CHANGE -->
  <tr>
    <th>Product Code</th>
    <th>Product Template</th>
    <th>Priority</th>
    <th>Window Product</th>
    <th>Description</th>
    <th>Actions</th>
  </tr>
  <tbody>
    <tr id="trendingDisplay" data-model="model-1">
      <td class="center-text">0001</td>
      <td>Template 1</td>
      <td class="center-text">1</td>
      <td class="center-text">Yes</td>
      <td>Description 1</td>
      <td>X</td>
    </tr>
    <tr id="trendingDisplay" data-model="model-2">
      <td class="center-text">0020</td>
      <td>Template 1</td>
      <td class="center-text">5</td>
      <td class="center-text">Yes</td>
      <td>Description 2</td>
      <td>X</td>
    </tr>
    <tr id="trendingDisplay" data-model="model-3">
      <td class="center-text">0300</td>
      <td>Template 3</td>
      <td class="center-text">1</td>
      <td class="center-text">No</td>
      <td>Description 3</td>
      <td>X</td>
    </tr>
    <tr id="trendingDisplay" data-model="model-4">
      <td class="center-text">4000</td>
      <td>Template 4</td>
      <td class="center-text">1</td>
      <td class="center-text">Yes</td>
      <td>Description 4</td>
      <td>X</td>
    </tr>
  </tbody>
</table>

您的.NET脚本将填充表格,您可能需要调整其循环以将data-model属性放置到每一行中.

Your .NET Script will populate the table, you may need to adjust it's loop to place the data-model attribute into each row.

jQuery

$(document).ready(function() {
  $('#MenuItem tbody').sortable({
    axis: 'y',
    update: function(event, ui) {
      //alert(ui.item.context.id);
      var order = 1;
      var model = [];

      $("#MenuItem tbody tr").each(function(key, elem) {
        model.push({
          id: $(elem).data("model"),
          ShuffleFunction: order
        });
        order++;
      });
      console.log(model);

      if (model.length > 1) {
        $.ajax({
          type: "POST",
          contentType: "application/json; charset=utf-8",
          //url: '@Url.Action("MoveFunction", "Product")', //This is my url put your url here and pass model as data it is an array of my items
          url: '/echo/json/',
          data: {
            json: JSON.stringify({
                model: model
              })
            },
          success: function(data) {
            //do something
            console.log(data);
          },
          error: function(e) {
            //do something
          }
        });
      }
    }
  });
});

对于jsfiddle示例,我使用了它们的/echo/json/网址,在这种情况下,它只是将json中的数据回传到data.

For the jsfiddle example, I used their /echo/json/ url, which just echos the data from json back to data in this case.

在移动项目并对其进行排序时,您可以打开控制台并查看模型阵列.如有疑问,请发表评论.

When you move an item, sorting it, you can then open the console and review the model array. If you have questions, comment.