Friday, April 18, 2014

Shopping cart in MVC

1:Make a database in SQL
USE [Ecommerce_DB]
GO
/****** Object:  Table [dbo].[TblProduct]    Script Date: 04/18/2014 17:19:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TblProduct](
[productid] [int] IDENTITY(1,1) NOT NULL,
[productcode] [varchar](250) NULL,
[Productname] [varchar](250) NULL,
[UnitPrice] [decimal](12, 2) NULL,
[StockQuantity] [int] NULL,
[CategoryId] [int] NULL,
[Images] [varchar](250) NULL,
PRIMARY KEY CLUSTERED
(
[productid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TblorderDetails]    Script Date: 04/18/2014 17:19:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TblorderDetails](
[OrderDetailsid] [int] IDENTITY(1,1) NOT NULL,
[Customerid] [varchar](250) NULL,
[OrderId] [int] NULL,
[ProductCode] [varchar](250) NULL,
[UnitPrice] [decimal](12, 2) NULL,
[Quantity] [int] NULL,
[TotalPrice] [decimal](12, 2) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Tblorder]    Script Date: 04/18/2014 17:19:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Tblorder](
[OrderId] [int] IDENTITY(1,1) NOT NULL,
[Customerid] [varchar](250) NULL,
[TotalPrice] [decimal](12, 2) NULL,
PRIMARY KEY CLUSTERED
(
[OrderId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TblCustomer]    Script Date: 04/18/2014 17:19:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TblCustomer](
[CustomerId] [int] IDENTITY(1,1) NOT NULL,
[Customername] [varchar](250) NULL,
[Country] [varchar](250) NULL,
[address] [varchar](250) NULL,
[UserName] [varchar](250) NULL,
[Password] [varchar](250) NULL,
PRIMARY KEY CLUSTERED
(
[CustomerId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Tblcategory]    Script Date: 04/18/2014 17:19:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Tblcategory](
[CategoryId] [int] IDENTITY(1,1) NOT NULL,
[SubcategoryId] [int] NULL,
[categoryname] [varchar](250) NULL,
PRIMARY KEY CLUSTERED
(
[CategoryId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Tblcart]    Script Date: 04/18/2014 17:19:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Tblcart](
[Cartid] [int] IDENTITY(1,1) NOT NULL,
[Customerid] [varchar](250) NULL,
[ProductCode] [varchar](250) NULL,
[UnitPrice] [decimal](12, 2) NULL,
[Quantity] [int] NULL,
[TotalPrice] [decimal](12, 2) NULL,
PRIMARY KEY CLUSTERED
(
[Cartid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

2:Create Model

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Ecommerce1_Pr.Models
{


    public class Cart
    {
        public string Customerid { get; set; }
        public string ProductCode { get; set; }
        public decimal UnitPrice { get; set; }
        public int Quantity { get; set; }
        public decimal TotalPrice { get; set; }
    }
    public class Products
    {
        public int ProductID;
        public string ProductName;
        public string ProductCode;
        public decimal Price;
        public string ProductImage;
        public int CategoryId;
        public int Quantity;
    }
    public partial class ShoppingCart
    {
        Ecommerce_DBEntities storeDB = new Ecommerce_DBEntities();
        string ShoppingCartId { get; set; }
        public const string CartSessionKey = "CartId";
        public static ShoppingCart GetCart(HttpContextBase context)
        {
            var cart = new ShoppingCart();
            cart.ShoppingCartId = cart.GetCartId(context);
            return cart;
        }
        // Helper method to simplify shopping cart calls
        public static ShoppingCart GetCart(Controller controller)
        {
            return GetCart(controller.HttpContext);
        }
        public void AddToCart(Products prmod)
        {
            // Get the matching cart and album instances
            var cartItem = storeDB.Tblcarts.SingleOrDefault(
                c => c.Customerid == ShoppingCartId
                && c.ProductCode == prmod.ProductCode);
            if (cartItem == null)
            {
                Tblcart c = new Tblcart();
                c.ProductCode = prmod.ProductCode;
                c.Customerid = ShoppingCartId;
                c.Quantity = prmod.Quantity;
                c.UnitPrice = prmod.Price;
                c.TotalPrice = prmod.Price * prmod.Quantity;
                storeDB.Tblcarts.Add(c);
            }
            else
            {
                // If the item does exist in the cart,
                // then add one to the quantity
                cartItem.Quantity = cartItem.Quantity + prmod.Quantity;
            }
            // Save changes
            storeDB.SaveChanges();
        }

        // We're using HttpContextBase to allow access to cookies.
        public string GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    context.Session[CartSessionKey] =
                        context.User.Identity.Name;
                }
                else
                {
                    // Generate a new random GUID using System.Guid class
                    Guid tempCartId = Guid.NewGuid();
                    // Send tempCartId back to client as a cookie
                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return context.Session[CartSessionKey].ToString();
        }
        public List<Cart> GetBasket(ShoppingCart  c1)
        {
            List<Cart> cc = new List<Cart>();
   
            var c = storeDB.Tblcarts.Where(p => p.Customerid == c1.ShoppingCartId);
            foreach (var ss in c.AsEnumerable<Tblcart>())
            {
                cc.Add(new Cart { Customerid = ss.Customerid, ProductCode = ss.ProductCode, UnitPrice = (decimal)ss.UnitPrice, Quantity = (int)ss.Quantity, TotalPrice = (decimal)ss.TotalPrice });


            }
            return cc;
        }
    }
}



3:Create Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ecommerce1_Pr.Models;
using System.Web.UI.HtmlControls;


namespace Ecommerce1_Pr.Controllers
{
    public class HomeController : Controller
    {      
        Ecommerce_DBEntities storeDB = new Ecommerce_DBEntities();
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult ProductCategory()
        {
            var ProductCategory = storeDB.Tblcategories;
            return View(ProductCategory);
        }
        public ActionResult Product(int id)
        {
            var Product = storeDB.TblProducts.Where(p => p.CategoryId == id);
            return View(Product);
        }
        [HttpPost]
        public ActionResult AddToCart(string PrCode, string Pcatid, string txtQuantity)
        {
            TblProduct p = storeDB.TblProducts.FirstOrDefault(ap => ap.productcode == PrCode);
            Products p1 = new Products();
            p1.ProductID = p.productid;
            p1.ProductCode = p.productcode;
            p1.ProductName = p.Productname;
            p1.Price = (Decimal)p.UnitPrice;
            p1.ProductImage = p.Images;
            p1.CategoryId = (int)p.CategoryId;
            p1.Quantity = Convert.ToInt32(txtQuantity);
                     
            var cart =Ecommerce1_Pr.Models.ShoppingCart.GetCart(this.HttpContext);
            cart.AddToCart(p1);
            return RedirectToAction("Product", "Home", new { id = Pcatid });
        }
        public ActionResult Productdetails(int id)
        {
            TblProduct p = storeDB.TblProducts.FirstOrDefault(ap => ap.productid == id);
            Products p1 = new Products();
            p1.ProductID = p.productid;
            p1.ProductCode = p.productcode;
            p1.ProductName = p.Productname;
            p1.Price = (Decimal)p.UnitPrice;
            p1.ProductImage = p.Images;
            p1.CategoryId = (int)p.CategoryId;
            return View(p1);
        }
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            LoginModel ln = new LoginModel();
            ViewBag.ReturnUrl = returnUrl;
            return View(ln);
        }    
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (CheckLogin(model))
                {
                    Response.Redirect("index");
                }
            }
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }
        public bool CheckLogin(LoginModel ln)
        {
            Session["CustomerId"] = "0";
            var c = storeDB.TblCustomers.Where(u => u.UserName == ln.UserName);
            if (c != null)
            {
                Session["CustomerId"] = ln.UserName;
                return true;
            }
            else { return false; }
        }
        public ActionResult ShoppingCart()
        {
            var cart = Ecommerce1_Pr.Models.ShoppingCart.GetCart(this.HttpContext);

            List<Cart> cc = null;
            ShoppingCart sc = new Models.ShoppingCart();
            cc = sc.GetBasket(cart);
            return View(cc);
        }
       
    }
}

No comments:

Post a Comment