In this way, buyers only need to drag the items they are interested in to their shopping cart, or delete items from the shopping cart while updating the overall price and quantity of the shopping cart.
Then let’s start the example. This example does not connect to the database to read data to initialize Products, but creates some virtual products as follows:
1. Create Product entity class
public class Product
{
public string Code { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public double Price { get; set; }
}
[code]
2. Construct product List
[code]
public class Product
{
public string Code { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public double Price { get; set; }
}
3. Create DataList and bind List
RepeatDirection="Horizontal" runat="server">
code='<%# Eval("Code") %>' id='item_<%# Container.ItemIndex 1 %>'>
<%# Eval( "Code") %>
<%# Eval("Name") %>
< ;li>
<%# Eval("Description") %>
$<%# Eval("Price") %> ;
private void BindData()
{
var products = GetProducts();
dlProducts.DataSource = products;
dlProducts.DataBind();
}
productItemStyle style name
Container.ItemIndex dynamically generates continuous Product number
4. Generate Products Div Draggable
Download the latest Jquery JS file and its UI file:
Div Draggable is generated when the page is initialized
$(document).ready(function() {
$(".productItemStyle").draggable({ helper: "clone" , opacity: "0.5" });
)};
5. Create a DropZone
DropZones are shopping cart areas
$(".dropZone").droppable(
{
accept: ".productItemStyle",
hoverClass: "dropHover",
drop: function(ev, ui) {
var droppedItem = ui.draggable.clone().addClass("droppedItemStyle");
var productCode = droppedItem[0 ].attributes["code"].nodeValue;
var productPrice =
getFormattedPrice(droppedItem[0].attributes["price"].nodeValue);
var removeLink = document.createElement("a" );
removeLink.innerHTML = "Remove";
removeLink.className = "deleteLink";
removeLink.href = "#";
removeLink.onclick = function()
{
$(".dropZone").children().remove("#" droppedItem[0].id);
updateTotal(productPrice * (-1));
}
droppedItem[0 ].appendChild(removeLink);
$(this).append(droppedItem);
updateTotal(productPrice);
}
}
);
Accept parameter: Display the Div with Class="productItemStyle"
hoverClass parameter: The style when a Product is placed in DropZone
Drop function: The function that starts when the Product is dragged and dropped into DropZone. This function mainly does Clone a Product Item, calculate the price, add a Remove button, and trigger events when the Remove button is clicked.
Price calculation updateTotal() function
// update the total!
function updateTotal(price) {
total = parseFloat(price);
$("#total").html(total.toFixed(2));
$(" .shoppingCartTotal").effect("bounce");
}
The final effect is as follows:
English original address: http://www.codeproject.com/KB/aspnet/JQueryShoppingCart.aspx