86267

How to Grab data from database using JQuery Sortable and post data back

Question:

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.

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.

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:

<img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/aBHxa.jpg" data-original="https://i.stack.imgur.com/aBHxa.jpg" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" />

Data Example:

<ol><li>cookie</li> <li>biscuit</li> <li>chocolate</li> </ol>

And after re-order by user:

<ol><li>chocolate</li> <li>biscuit</li> <li>cookies</li> </ol>

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

Answer1:

I commented out the following line:

alert(ui.item.context.id);

I think you meant:

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

Or maybe:

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

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.

Working Example: <a href="https://jsfiddle.net/Twisty/45dw9fve/3/" rel="nofollow">https://jsfiddle.net/Twisty/45dw9fve/3/</a>

<strong>HTML</strong>

<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>

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

<strong>jQuery</strong>

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

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.

Recommend

  • WooCommerce shortcode products list
  • Instagram Follower Count - Using jQuery / json & PHP
  • Onclick is not working
  • Loading Json as variable into jsTree
  • java.lang.IllegalStateException: getInputStream() has already been called for this request + Struts2
  • Whats the best way of persisting data to Isolated Storage on Windows Phone 7?
  • Select value from xtype selection type checkbox CQ5
  • Elasticsearch script query involving root and nested values
  • Why use database factory in asp.net mvc?
  • How do I configure context broker accept post requests from my remote sensor?
  • saving file generated by TCPDF
  • Force show.bind execution
  • wxPython: displaying multiple widgets in same frame
  • What does 'Language neutral' mean with regard to MAKELANGID?
  • how to save the state in userdefaults of accessory checkmark-iphone
  • Chart.js Multiple dataset
  • Groovy: Unexpected token “:”
  • Android - Material Design - NavigationView - How to put vertical scroll?
  • How to write order and limit within cakephp joins array
  • Custom validator control occupying space even though display set to dynamic
  • Word Open XML Mail Merge
  • Android fill_parent issue
  • FileReader+canvas image loading problem
  • Is there a javascript serializer for JSON.Net?
  • Pass value from viewmodel to script in zk
  • Using $this when not in object context
  • Sails.js/waterline: Executing waterline queries in toJSON function of a model?
  • Deselecting radio buttons while keeping the View Model in synch
  • Getting last autonumber in access
  • Counter field in MS Access, how to generate?
  • Incrementing object id automatically JS constructor (static method and variable)
  • Javascript Callbacks with Object constructor
  • How to check if every primary key value is being referenced as foreign key in another table
  • Can I have the cursor start on a particular column by default in jqgrid's edit mode?
  • jquery mobile loadPage not working
  • How to delete a row from a dynamic generate table using jquery?
  • json Serialization in asp
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • How to stop GridView from loading again when I press back button?
  • Is it possible to post an object from jquery to bottle.py?