how to manage shopping cart sessions without login


In MVC - In E commerce - how to add products in add to cart without Login and managed this session after Login and also show those products which are added before Login Like Flipkart and Amazon.

its very urgent for me because my site is delay for this.

 

Regard's

Hemant Modi 


Asked by:- HEMANTMODI
1
: 1289 At:- 6/7/2017 4:57:23 PM
asp.net mvc sql javascript json

Hemant , can you use Sessions for this? Or it is not allowed? 0
By : vikas_jk - at :- 6/7/2017 5:07:42 PM





2 Answers
profileImage Answered by:- vikas_jk

Hemant, I have solution for you, maybe it is correct for your requirement

Step 1: If someone adds a product in shopping cart, save a cookie in user browser, you can use javascript/jquery to save cookie in users browser

function createCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}


$(document).ready(function(){

//Create Cookie for 1 year, when user add's a product
createCookie('ppkcookie','Unique_Guid',365);

//Save Cookie Unique_Guid in database, with product using ajax call

//getCookie
var x = readCookie('ppkcookie')
if (x) {
   // do something here, like load shopping cart products from database using ajax
}

})

Step 2: Save products in database with unique_id(if user add a product in cart), and fetch products from database where unique_id matches

Let me know if this work's for you, thanks

2
At:- 6/7/2017 5:53:41 PM


profileImage Answered by:- Vinnu

@Vikas's method should work if you can store data on client side, you can also store data on client side using javascript localstorage also.

You can also store cart details in C# sessions, here is the method step by step

  1. Create a Model for Product
    public class Product {
     public string Id {get;set;}
     public string Name { get; set;}
     public double Price { get; set;}
     public string Photo { get;set;}
    }?
  2. Create another Model for saving Item/product and it's quantity
    public class Item
    {
     public Product Product{get;set;}
     public int Quantity{get;set;}
    }?
  3. Let's add the dummy data for Products
     public class ProductModel {
      private List <Product> products;
    
      public ProductModel() {
       this.products = new List < Product > () {
        new Product {
         Id = "p01",
          Name = "Name 1",
          Price = 5,
          Photo = "thumb1.gif"
        },
        new Product {
         Id = "p02",
          Name = "Name 2",
          Price = 2,
          Photo = "thumb2.gif"
        },
        new Product {
         Id = "p03",
          Name = "Name 3",
          Price = 6,
          Photo = "thumb3.gif"
        }
       };
      }
    
      public List <Product> findAll() {
       return this.products;
      }
    
      public Product find(string id) {
       return this.products.Single(p => p.Id.Equals(id));
      }
    
     }?
  4. Now, create the C# controller function to add/remove  item from Cart with Session
    //id is product Id
     public ActionResult Buy(string id)
            {
                ProductModel productModel = new ProductModel();
                //check if session with cart is empty
                if (Session["cart"] == null)
                {
                    List<Item> cart = new List<Item>();
                    cart.Add(new Item { Product = productModel.find(id), Quantity = 1 });
                    Session["cart"] = cart;
                }
                // if Session["cart"] already have data
                else
                {
                    List<Item> cart = (List<Item>)Session["cart"];
                    int index = isExist(id);
                    if (index != -1)
                    {
                        cart[index].Quantity++;
                    }
                    else
                    {
                        cart.Add(new Item { Product = productModel.find(id), Quantity = 1 });
                    }
                    Session["cart"] = cart;
                }
                return RedirectToAction("Index");
            }
    
            public ActionResult Remove(string id)
            {
                List<Item> cart = (List<Item>)Session["cart"];
                int index = isExist(id);
                cart.RemoveAt(index);
                Session["cart"] = cart;
                return RedirectToAction("Index");
            }
    
            private int isExist(string id)
            {
                List<Item> cart = (List<Item>)Session["cart"];
                for (int i = 0; i < cart.Count; i++)
                    if (cart[i].Product.Id.Equals(id))
                        return i;
                return -1;
            }?
  5. You can list Cart details in your View using Razor code as below
    <table cellpadding="2" cellspacing="2" border="1">
            <tr>
                <th>Option</th>
                <th>Id</th>
                <th>Name</th>
                <th>Photo</th>
                <th>Price</th>
                <th>Quantity</th>
                <th>Sub Total</th>
            </tr>
            @foreach (Item item in (List<Item>)Session["cart"])
            {
                <tr>
                    <td><a href="@Url.Action("Remove", "Cart", new { id = item.Product.Id })">Remove</a></td>
                    <td>@item.Product.Id</td>
                    <td>@item.Product.Name</td>
                    <td><img src="~/Content/Images/@item.Product.Photo" width="60" /> </td>
                    <td>@item.Product.Price</td>
                    <td>@item.Quantity</td>
                    <td>@(item.Product.Price * item.Quantity)</td>
                </tr>
            }
            <tr>
                <td align="right" colspan="6">Sum</td>
                <td>
                    @{
                        List<Item> cart = (List<Item>)Session["cart"];
                        var total = cart.Sum(item => item.Product.Price * item.Quantity);
                    }
                    @total
                </td>
            </tr>
        </table>?

Now, as you can see i am not saving any details in database and using Session["cart"] for saving details but I would like to advice you, use a Guid for saving details in cart like Sessaion["123456-67800"], where "123456-67800" is a Guid created using Guid.NewGuid(), and save this Guid in user's localStorage using javascript code

localStorage.setItem('CartGUID','123455-67800');

as soon as your E-commerce page is loaded check if there is any localStorage with CartGuid using javascript code

var cartGuid= localStorage.getItem('CartGUID');
if(cartGuid != null)
{
   //load partial view for above guid(123456-67800) cart
}

if there is already Guid created load items in your cart, that's it, you are done.

0
At:- 5/22/2018 2:38:22 PM Updated at:- 5/22/2018 2:39:10 PM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use