Hi I'm having a problem implementing a mini shopping cart drop down in the header to show the user all the products they have in their shopping cart. It seems the only solution for this is Ajax, and I've looked all over and can't find anything that I could possibly use with web forms.

At the moment I've managed to populate a shopping cart entity with the customer's products, and in that entity I have a customer guid which is stored as cookie and in the database to keep track of the user and their products.

The problem I am having, as previously mentioned is showing customer the products they have in their shopping without them having to be directed to another page, kind of like how most of the online shops these days are doing it.

so far this is what I've tried and it's not working:

<div class="shopping-cart" style="background-color:#808080">
    <div class="shopping-cart-header">
        <i class="fa fa-shopping-cart cart-icon" aria-hidden="true"></i>
        <span class="badge"></span>
        <div class="shopping-cart-total">
            <span class="lighter-text">Total:</span>
            <span class="main-text"> $5000</span>
        </div>
    </div>
  <asp:ListView
    ID="shoppingCartListView"
    runat="server"
    DataKeyNames="Id"
    ItemType="OnlineShoppingApplication.DataAccess.ShoppingCartItem"
      ItemPlaceholderID="shopping_cart"
    SelectMethod="GetShoppingCartItems">
    <EmptyDataTemplate>
    <p class="main-text">0 Items in cart</p>
    </EmptyDataTemplate>
      <EmptyItemTemplate>
      <p class="main-text">0 Items in cart</p>
      </EmptyItemTemplate>

 <ItemTemplate>
      <ul class="shopping-cart-items">
            <li class="clear-fix">
            <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/195612/cart-item1.jpg" alt="Item1"/> 
            <div class="item-details">
             <span class="item-name"><%#:Item.PWItem.PWItemDescription%></span>
             <span class="item-price"><%#:Item.PWItem.PWItemDetails.FirstOrDefault().PWItemDetailRetailPrice %></span>
             <span class="item-quantity"><%#Item.Quantity %></span>
            </div>
            </li>
  </ul>
 </ItemTemplate>
  <LayoutTemplate>
  <div runat="server" id="shopping_cart">
  </div>
  </LayoutTemplate>
 </asp:ListView>
</div> <%--End of mini shopping cart(global)--%>

 <div class="navbar-second-layer">
           <div class="container">
            <div class="navbar-collapse collapse" id="product-details-second-navbar-layer">
               <ul class="nav navbar-nav navbar-left" style="letter-spacing:1.3px;color:#ffffff">
                        <li><a runat="server" style="color:#ffffff;" href="#">&nbsp;Home</a></li>
                        <li><a runat="server"  style="color:#ffffff;"  href="#">&nbsp;Women</a></li>
                        <li><a runat="server" style="color:#ffffff;" href="#">&nbsp;Men</a></li>
                        <li><a runat="server" style="color:#ffffff;" href="#">&nbsp;Kids</a></li>
                        <li><a runat="server" style="color:#ffffff;" href="#">&nbsp;Brands</a></li>
                   <li class="visible-xs"><a runat="server"  style="color:#ffffff;" data-toggle="dropdown" href="#"><span class="glyphicon glyphicon-user"></span>&nbsp;Log in</a></li>
                    <li class="visible-xs"><a runat="server"  style="color:#ffffff;" href="#"><span class="glyphicon glyphicon-gift"></span>&nbsp;Wish List<span id="wish_list_count_mobile" class="badge" runat="server"></span></a></li>
                   <li class="visible-xs"><a runat="server"  style="color:#ffffff;" href="#"><span class="glyphicon glyphicon-shopping-cart"></span>&nbsp;Cart<span id="cart_list_count_mobile" class="badge" runat="server"></span></a></li>
                    </ul>
                 </div>
            </div> <%--End of navbar second layer--%>
    </div> <%--End of navbar second layer, container--%>
  </div>
</header> <%--End of header section global--%>

Above is the code I have in my site.master page, I tried using a listview in the header section in of the site.master and the select method for listview is "GetShoppingCartItems" when there's no items in the cart it says '0 items in cart' as specified as soon as I click 'add to cart', the text '0 items in cart' disappears but it does not show the cart items.

Heres the select method:

public IQueryable<ShoppingCartItem> GetCartItems()
    {
        if (CustomerCreated())
        {
            CustomerGuid = _customer.CustomerGuid;
            var shoppingCart = _db.ShoppingCartItems.Where
                              (c => c.Customer.CustomerGuid == CustomerGuid);
            return shoppingCart;
        }
        else
            return null;

    }

Heads up, I know I could go with open source e-commerce solutions but I'm not at the level where I could possibly manipulate their code and create plugins.
Thanks in advance. :)

Dani AI

Generated

a couple of concrete fixes will get this working without a full page redirect.

First, your ListView is in Site.master, so the SelectMethod must live in Site.master.cs (or use a DataSource control). Also, your markup says SelectMethod="GetShoppingCartItems" while the method you posted is GetCartItems; those must match exactly. Finally, put the UL in the LayoutTemplate and the LI in the ItemTemplate so the placeholder actually emits items.

<asp:ListView ID="lvMiniCart" runat="server"
    ItemType="YourNamespace.ShoppingCartItem"
    SelectMethod="GetShoppingCartItems"
    ItemPlaceholderID="ph">
  <LayoutTemplate>
    <ul class="shopping-cart-items"><asp:PlaceHolder runat="server" ID="ph" /></ul>
  </LayoutTemplate>
  <ItemTemplate>
    <li>
      <span class="item-name"><%#: Item.PWItem.PWItemDescription %></span>
      <span class="item-quantity"><%#: Item.Quantity %></span>
      <span class="item-price"><%#: Item.UnitPrice %></span>
    </li>
  </ItemTemplate>
  <EmptyDataTemplate><p class="main-text">0 items in cart</p></EmptyDataTemplate>
</asp:ListView>

If you also want true Ajax (no full postback), expose a tiny WebMethod and refresh the mini-cart on demand. This keeps your header decoupled from page logic, as hinted, but stays asynchronous.

// CartApi.aspx.cs
[WebMethod] public static MiniCartDto GetMiniCart() {
  var guid = GetGuidFromCookie(); // server-side only
  using (var db = new AppDbContext()) {
    var items = db.ShoppingCartItems
      .Where(x => x.Customer.CustomerGuid == guid)
      .Select(x => new CartItemDto {
        Name = x.PWItem.PWItemDescription,
        Qty  = x.Quantity,
        Price = x.PWItem.PWItemDetails.Select(d => d.PWItemDetailRetailPrice).FirstOrDefault() ?? 0m
      }).ToList();
    return new MiniCartDto {
      Count = items.Sum(i => i.Qty),
      Total = items.Sum(i => i.Price * i.Qty),
      Items = items
    };
  }
}
public class CartItemDto { public string Name; public int Qty; public decimal Price; }
public class MiniCartDto { public int Count; public decimal Total; public List<CartItemDto> Items; }
function refreshMiniCart() {
  $.ajax({
    url: 'CartApi.aspx/GetMiniCart',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json'
  }).done(function (res) {
    var c = res.d;
    $('.shopping-cart .badge').text(c.Count);
    $('.shopping-cart .main-text').text('$' + c.Total.toFixed(2));
    var $ul = $('.shopping-cart-items').empty();
    c.Items.forEach(function (it) {
      $ul.append('<li><span class="item-name">'
        + it.Name + '</span><span class="item-quantity">'
        + it.Qty + '</span><span class="item-price">'
        + it.Price.toFixed(2) + '</span></li>');
    });
  });
}

Notes: never trust a GUID from the client; read it server-side. Guard against nulls (your FirstOrDefault can be null). Avoid synchronous XHR; async calls keep the UI responsive. If you do state-changing calls (add/remove), include CSRF protection.

Recommended Answers

All 6 Replies

anybody?

There is XMLHttpRequest's open and send methods in Javscript. Open method has a boolean parameter so the call can be done synchonous or asynchronous (Click Here. BTW, looks like the image in line 27, has something to do with a product in the shopping cart.

Thank you for responding!!!!!!, you're the first person I posted this question on stack overflow as well, and you're the only person that atleast gave me a response. oh btw the image is just a sample that I was using from amazon, has nothing to do with a shopping cart. I have 2 issues I don't really know how to use ajax, but I know ajax is the solution to my problem and I don't know where to place a method for ajax to call to populate the mini shopping cart and if its.

Well, I am pleased, but probably there is code behind in order to be more specific.

The code that I provided is all that I use to get a users shopping cart, there's really no other method I have besides the one that just calls that method. Oh and by the way I made a mistake in my last post in the last sentence I mean't to say I have 2 issues I don't really know how to use ajax, but I know ajax is the solution to my problem and I don't know where to place a method for ajax to call to populate the mini shopping cart and if its secure.. even if you could just show me a simple example of how a call is made to a database and the results of that call are used to populate an element I would really appreciate it. :)

Googling https://www.google.es/#q=asp.net+ajax+tutorial and reading a tutorial is a good start if you know asp.net. In case there's no asp.net notion, the first step would be asp.net learning and so, an asp.net tuturial.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.