【问题标题】:How to Grab data from database using JQuery Sortable and post data back如何使用 JQuery Sortable 从数据库中获取数据并将数据发回
【发布时间】:2016-10-10 13:40:21
【问题描述】:

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

这是我的可排序代码,除了var objmodel 的行之外,它都可以工作。创建此变量时,它设法从数据库中获取一个空对象,并使用新的 shuffle 函数值填充空对象(检查图像链接)。我需要它做的是抓取用户点击的对象,然后用新订单填充该对象。

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

数据示例:

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

在用户重新订购后:

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

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

 $(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++;
        }

    }

【问题讨论】:

  • 为测试创建了一个工作示例:jsfiddle.net/Twisty/45dw9fve 我发现的第一个问题,ui.item.context 未定义。这个对象应该是什么?
  • 其次,您调用Id: ui.item.data("model"),但您的tr 元素上没有数据属性,在这种情况下是ui.item。但是您是在 ForEach 循环中执行此操作的,因此每次都会重新编写它。我怀疑您想迭代每一行,收集新订单和相关模型。

标签: jquery ajax asp.net-mvc-4 asp.net-ajax jquery-ui-sortable


【解决方案1】:

我把下面这行注释掉了:

alert(ui.item.context.id);

我想你的意思是:

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

或许:

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

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

工作示例: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 属性放入每一行。

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

当您移动一个项目并对其进行排序时,您可以打开控制台并查看模型数组。如果您有任何问题,请发表评论。

【讨论】:

  • 您对示例进行了硬编码,因为我上面的数据示例是从数据库中提取的。我现在要做的是编辑这些数据并将其打包发布到数据库中。我检查了控制台,它显示了带有 ID 的数组,但是它们都是空的,而不是 db 数据。
  • @cazlouise 请编辑您的帖子并包含由您的 ASP.NET 脚本呈现的源 HTML 示例。 JavaScript 是一种客户端脚本语言,因此它与从服务器发回的结果 HTML 一起工作。这就是为什么我的示例如您所说的那样是“硬编码”的。这是对您生成的 HTML 可能是什么样子的猜测。
  • 由我的 ASP.NET 脚本呈现的源 html 嵌入在我的 html 中的表中
  • 是的,您可以在帖子中添加一些内容吗?
猜你喜欢
  • 2017-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-03
  • 2013-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多