In the last article we demonstrated how to get started with the drag and drop functionality using the jQuery library. In this article we will persist the user selections or dragged items into the database and then repopulate the shopping cart.

Recommended Reading:

It is highly recommended that you read the first part of the article. There is also a screencast which shows how to get started with jQuery drag and drop functionality.

1) Implementing Drag and Drop Using jQuery Part 1
2) Screencast: Implementing Drag and Drop Using jQuery

Persisting User Selection:

In the first part of this article we did not implement any code to persist the user selection. This means if the user drag and drop items into the shopping cart and refresh the page the shopping cart will come out empty. There are many ways of persisting the user selected items and we will choose the database route. This means every time a user drag and drop an item in the shopping cart it will be persisted into the database table. You can consider this as an staging table since the user has not yet performed the final checkout. The staging table schema looks like the following:



The JQuery droppable method has a drop event which is fired whenever the items are dropped into the shopping cart. Here is the implementation of the drop event:



Inside the drop event we extract the productCode out of the UL element and use jQuery Ajax API to make a call to the SaveProduct method. The $.toJSON function is used to convert an object to JSON representation. The SaveProduct method is implemented below:



In the next section we will demonstrate how to repopulate the shopping cart with the items in the database.

Re-Populating Shopping Cart with Items:

In the last section we discussed how items can be added to the database using Ajax calls. In this section we are going to retrieve the items from the database and then populate the shopping cart. The loadProductsForUser is fired as soon as the DOM is loaded. The purpose of the loadProductsForUser function is to fetch the items for the user and then populate the shopping cart. The implementation of the function is shown below:



The GetProductByUserName is used to fetch the products from the database. Once, the items are fetched they are appended to the shopping cart DIV element. The GetProductByUserName implementation is shown below:



The method above uses LINQ to SQL to retrieve the products by using user name. The products are serialized and then returned to the client side.

The following screenshot shows the result:



Conclusion:

In this article we learned how to persist the selected products into the database and then retrieve the products and display them in the shopping cart. In the next article we are going to take a look at calculating the total of the items added to the shopping cart and adding duplicating products.

[Download Sample