ASP.NET Shopping Cart


Today I am going to give you a significant example. ASP.NET Shopping Cart.
 I have used SQL stored procedure for retrieving data. Entity framework code first models.
I'll explain how to do it.

As a usual way, please create the project.

I'll explain by example. Here is available user registration
user login.
Adding new items (this is allowed to admin user).
My cart.
You can search for any items.
You can sort items in ascending order.

Let's start example
Now you should add entity framework to your project.
Go to tools>>
Library package manager>>
Manage NuGet packages for solution>>
Search entity framework and install.

Need to create Folders inside the solution.following are the names.
DAL
Model
Img (for saving images)
Slideshow (slideshow images)


Now first, let's create model classes.

Add items model is like this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace EFWebApplication1.Models
{
public class AddItemsModels
{
[Key]
public int ItemID { get; set; }
public string ItemName { get; set; }

public string ItemDescription { get; set; }
public int Price { get; set; }

}
}





Add to cart model is like this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace EFWebApplication1.Models
{
public class AddToCartModels
{
[Key]
public int CartID { get; set; }
public int ItemID { get; set; }
public string UserID { get; set; }

}
}

 


Now create context classes.
I have created two context classes. These should be created inside DAL folder.

Catcontext class is like this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using EFWebApplication1.Models;

namespace EFWebApplication1.DAL
{
public class CatContext:DbContext
{
public CatContext():base ("name=ShoppingCart")
{

}
//public DbSet<UserReister> UserReister { get; set; }
//public DbSet<LoginDetails> LoginDetails { get; set; }
public DbSet<AddToCartModels> AddToCartModels { get; set; }
public DbSet<AddItemsModels> AddItemsModels { get; set; }
}
}

 

View data context class   is like this. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace EFWebApplication1.DAL
{
public class ViewDataContext
{
public static string SqlConnection = "Data Source=My-PC;Initial Catalog=ShoppingCartDB;Integrated Security=True";
}
}
 
 


You should add images to the Img folder.

Images' name should be like this.
Ex: 1.jpg

Then add some images to the slideshow folder

Images name should be like this.
Ex: B0.jpg

Now add the connection string section into the web config file.
Comment the existing connection string.


This should be added inside to the connection string tag.

<add name="ShoppingCart" connectionString="Data Source=My-PC;Database=ShoppingCartDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

ex:
<connectionStrings>
<add name="ShoppingCart" connectionString="Data Source=My-PC;Database=ShoppingCartDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
 
</connectionStrings>




Need to create 3 pages.  When we add these files, we should add web form with master page.
Names are the following.
Additems.
Shoppingitems
Mycart.

Now we should look at these pages to the navigation bar.



Open the site. Master front end page.
Add these yellow color parts only to the navigation section.

<ul class="nav navbar-nav">
   <li><a runat="server" href="~/">Home</a></li>

   <li ><a id="SI" runat="server" href="~/ShoppingItems" >ShoppingItems</a></li> 
    <li><a id="AI" runat="server" href="~/AddItems">AddItems</a></li>
    <li ><a id="MYC" runat="server" href="~/MyCart" >MyCart</a></li>

     <li><a runat="server" href="~/About">About</a></li>
     <li><a runat="server" href="~/Contact">Contact</a></li>

</ul>


Now go to the site. Master code-behind file.

At these to the page load event.
Add this namespace. 

using EFWebApplication1.Models;


 string un = Context.User.Identity.Name;
            if(un =="")
            {
                SI.Visible = false;
                MYC.Visible = false;
            }
            else
            {
                SI.Visible = true;
                MYC.Visible = true;
            }

            if (un == "Admin")
            {
                AI.Visible = true;
            }
            else
            {
                AI.Visible = false;
            }


 Add item front end page like this.

 <div class="form-horizontal">
        <h4>Create a new account.</h4>
        <hr />
        <asp:ValidationSummary runat="server" CssClass="text-danger" />
        <div class="form-group">
            <asp:Label AssociatedControlID="ItemName" runat="server"  CssClass="col-md-2 control-label">ItemName</asp:Label>
            <div class="col-md-10">
            <asp:TextBox runat="server" ID="ItemName"  CssClass="form-control"></asp:TextBox>
                </div>
        </div>
      
        <div class="form-group">
            <asp:Label AssociatedControlID="ItemDescription" runat="server" CssClass="col-md-2 control-label">ItemDescription </asp:Label>
            <div class="col-md-10">
                <asp:TextBox ID="ItemDescription" runat="server" CssClass="form-control"></asp:TextBox>
            </div>
        </div>

        <div class="form-group">
            <asp:Label AssociatedControlID="Price" runat="server"  CssClass="col-md-2 control-label">Price</asp:Label>
            <div class="col-md-10">
                <asp:TextBox ID="Price" runat="server" CssClass="form-control"></asp:TextBox>
            </div>
        </div>
     
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <asp:Button runat="server" ID="AddItems" Text="AddItems" CssClass="btn btn-default" OnClick="AddItems_Click"  />
            </div>
        </div>

    </div>

Add item code-behind file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EFWebApplication1.DAL;
using EFWebApplication1.Models;
using System.Data.SqlClient;

namespace EFWebApplication1
{
public partial class AddItems : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void AddItems_Click(object sender, EventArgs e)
{

SqlConnection con = new SqlConnection();
con.ConnectionString = DAL.ViewDataContext.SqlConnection;

con.Open();
string insertQuery = "insert into AddItemsModels(ItemName,ItemDescription,Price)values (@ItemName,@ItemDescription,@Price)";
SqlCommand cmd = new SqlCommand(insertQuery, con);
cmd.Parameters.AddWithValue("@ItemName", ItemName.Text);
cmd.Parameters.AddWithValue("@ItemDescription", ItemDescription.Text);
cmd.Parameters.AddWithValue("@Price", Price.Text);

try
{
cmd.ExecuteNonQuery();
con.Close();
string msg = "Successfully Saved";
Response.Write("<script>alert('" + msg + "')</script>");
ItemName.Text = "";
ItemDescription.Text = "";
Price.Text="";
}
catch (SqlException ex)
{
Response.Write("<script>alert('" + ex + "')</script>");
Response.Write(ex);
}
}
}
}


Shopping item front end page

 <div>
<h4>Welcome To Buy any thing</h4>



<div class="form-group">

<div class="col-md-10" >

<asp:TextBox runat="server" ID="Search" CssClass="form-control" Width="322px" ></asp:TextBox>
<asp:Button runat="server" ID="Searchbtn" style="margin-left: 284px;margin-top: -55px;background:#E62E04;" Text="Search" CssClass="btn btn-default" OnClick="Searchbtn_Click" />
</div>
<div>
<asp:Button runat="server" ID="sortbtn" style="margin-left: -580px;color: blue;position: absolute;padding-top: 10px;background:#FD9729;" Text="Sort By Price" CssClass="btn btn-default" OnClick="sortbtn_Click" />
<asp:Button runat="server" ID="cartcount" style="margin-left: -460px;color: blue;position: absolute;padding-top: 10px;background:#FF5400;" Text="" CssClass="btn btn-default" />
</div>

<br />
<div>
<asp:Repeater ID="rptCustomers" runat="server" OnItemCommand="rptCustomers_ItemCommand">
<HeaderTemplate>
<table border="1">
<tr>
<th>

</th>
<th scope="col" style="width: 80px">

</th>
<th scope="col" style="width: 120px">

</th>
<th scope="col" style="width: 100px">

</th>
<th>

</th>

</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<img itemprop="image" id="ItemID" class="picCore pic-Core-v"
src="Img/<%# Eval("ItemID") %>.jpg" />
</td>
<td>
<div style="color:red;font-weight:900;margin-top: -110px;">Item Name:</div>
<asp:Label ID="ItemName" runat="server" Text='<%# Eval("ItemName") %>' />
</td>
<td>
<div style="color:red;font-weight:900;margin-top: -59px;">Item Description:</div>
<asp:Label ID="ItemDescription" runat="server" Text='<%# Eval("ItemDescription") %>' />
</td>
<td>
<div style="color:red;font-weight:900;position: absolute;margin-top: -93px;">Price:</div>
<div style="position: absolute;margin-top: -68px;"><asp:Label ID="Price" runat="server" Text='<%# Eval("Price") %>' /></div>
</td>
<asp:Label ID="lblID" runat="server" Text='<%#Eval("ItemID") %>' Visible="False" />
<td>
<div id="BT" runat="server">
<div class="col-md-offset-2 col-md-10">
<div >
<asp:Button ID="addcat" runat="server" Text="Add To Cart " CssClass="btn btn-default" Style="background-color :#FF5400;" OnClick="Unnamed1_Click1" />
<asp:Button runat="server" Text="Buy Now" CssClass="btn btn-default" Style="background-color :#FD9729;" OnClick="Unnamed1_Click" />
</div>

</div>

</div>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
<div>
<%--paging reapeter--%>
<asp:Repeater ID="rptPager" runat="server">
<ItemTemplate>
<asp:LinkButton ID="lnkPage" style="font-size:x-large" runat="server" Text='<%#Eval("Text") %>' CommandArgument='<%# Eval("Value") %>'
CssClass='<%# Convert.ToBoolean(Eval("Enabled")) ? "page_enabled" : "page_disabled" %>'
OnClick="Page_Changed" OnClientClick='<%# !Convert.ToBoolean(Eval("Enabled")) ? "return false;" : "" %>'></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
</div>
</div>
</div>

Shopping item Code behind file 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Microsoft.AspNet.Identity;
using System.Collections;

namespace EFWebApplication1
{
public partial class ShoppingItems : System.Web.UI.Page
{
public string itemval;
public string UID;
public string sortkey;
private int PageSize = 5;
protected void Page_Load(object sender, EventArgs e)
{

if (!Request.IsAuthenticated)
{

string un = Context.User.Identity.Name;

if (un == "")
{

}
else
{

}

}

if (!this.IsPostBack)
{
//Call to the two following methods
this.BindRepeater(1);
CartItemCount();
}
}
//this is a method calling to ViewCartDetails stored procedure
private void CartItemCount()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = DAL.ViewDataContext.SqlConnection;

//Getting login userID
var userId = User.Identity.GetUserId();
SqlCommand cmd = new SqlCommand();
try
{
con.Open();
//execute ViewCartDetails procedure
cmd = new SqlCommand("ViewCartDetails", con);
cmd.CommandType = CommandType.StoredProcedure;
//passing UserID to sql procedure
cmd.Parameters.Add(new SqlParameter("@UserID", userId));
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
rptCustomers.DataSource = dt;
rptCustomers.DataBind();

if (dt.Rows.Count > 0)
{
//getting ItemCount field value from the stored procedure
cartcount.Text =dt.Rows[0]["ItemCount"].ToString() + " Items In Cart" ;

}

}
catch (SqlException ex)
{
Response.Write("<script>alert('" + ex + "')</script>");
Response.Write(ex);
}
}

private void BindRepeater(int pageIndex)
{

SqlConnection con = new SqlConnection();
con.ConnectionString = DAL.ViewDataContext.SqlConnection;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("ViewAllShoppingItems", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ItemName", Search.Text);
//paging items start
cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
cmd.Parameters.AddWithValue("@PageSize", PageSize);
cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4);
cmd.Parameters["@RecordCount"].Direction = ParameterDirection.Output;
//paging items end
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
rptCustomers.DataSource = dt;
rptCustomers.DataBind();
//paging ... getting record count from the procedure
int recordCount = Convert.ToInt32(cmd.Parameters["@RecordCount"].Value);
this.PopulatePager(recordCount, pageIndex);
}

protected void Unnamed1_Click(object sender, EventArgs e)
{
Response.Write("<script>alert('Thank you for buying this Item')</script>");
}

protected void Unnamed1_Click1(object sender, EventArgs e)
{
var userId = User.Identity.GetUserId();//getting login user ID
UID = userId;
//Find the button control
var btn = (Button)sender;
//Get the repeater selected row
var item = (RepeaterItem)btn.NamingContainer;
//FInd the control from row
var IdValue = ((Label)item.FindControl("lblID")).Text;

itemval = IdValue;
AddingToCart();

}

private void AddingToCart()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = DAL.ViewDataContext.SqlConnection;

con.Open();
string insertQuery = "insert into AddToCartModels(ItemID,UserID)values (@ItemID,@UserID)";
SqlCommand cmd = new SqlCommand(insertQuery, con);
cmd.Parameters.AddWithValue("@ItemID", itemval);
cmd.Parameters.AddWithValue("@UserID", UID);
try
{
cmd.ExecuteNonQuery();
con.Close();
//string msg = "Item Added To the Cart";
//Response.Write("<script>alert('" + msg + "')</script>");
}
catch (SqlException ex)
{
Response.Write("<script>alert('" + ex + "')</script>");
Response.Write(ex);
}

}
protected void rptCustomers_ItemCommand(object source, RepeaterCommandEventArgs e)
{

}


protected void Searchbtn_Click(object sender, EventArgs e)
{
BindRepeater(1);
}

protected void sortbtn_Click(object sender, EventArgs e)
{

Sortorder(1);
}
private void Sortorder(int pageIndex)
{

SqlConnection con = new SqlConnection();
con.ConnectionString = DAL.ViewDataContext.SqlConnection;

con.Open();
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("ViewShoppingItems", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
cmd.Parameters.AddWithValue("@PageSize", PageSize);
cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4);
cmd.Parameters["@RecordCount"].Direction = ParameterDirection.Output;

SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
rptCustomers.DataSource = dt;
rptCustomers.DataBind();
int recordCount = Convert.ToInt32(cmd.Parameters["@RecordCount"].Value);
this.PopulatePager(recordCount, pageIndex);
}
//paging.. method
private void PopulatePager(int recordCount, int currentPage)
{
double dblPageCount = (double)((decimal)recordCount / Convert.ToDecimal(PageSize));
int pageCount = (int)Math.Ceiling(dblPageCount);
List<ListItem> pages = new List<ListItem>();
if (pageCount > 0)
{
for (int i = 1; i <= pageCount; i++)
{
pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
}
}
rptPager.DataSource = pages;
rptPager.DataBind();
}
//page change icon event.
protected void Page_Changed(object sender, EventArgs e)
{
int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
this.BindRepeater(pageIndex);
}
}

 My cart front end page

<div>
<h4>My Cart</h4>
<h3><asp:Label ID="Label2" runat="server" Text=""></asp:Label>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label></h3>
<asp:Repeater ID="rptCustomers" runat="server" OnItemCommand="rptCustomers_ItemCommand" >
<HeaderTemplate>
<table border="1">
<tr>
<th>
</th>
<th scope="col" style="width: 80px">

</th>
<th scope="col" style="width: 120px">

</th>
<th scope="col" style="width: 100px">

</th>
<th>

</th>

</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<img itemprop="image" id="ItemID" class="picCore pic-Core-v"
src="Img/<%# Eval("ItemID") %>.jpg" />
</td>
<td>
<div style="color:red;font-weight:900;margin-top: -110px;">Item Name:</div>
<asp:Label ID="ItemName" runat="server" Text='<%# Eval("ItemName") %>' />
</td>
<td>
<div style="color:red;font-weight:900;margin-top: -59px;">Item Description:</div>
<asp:Label ID="ItemDescription" runat="server" Text='<%# Eval("ItemDescription") %>' />
</td>
<td>
<div style="color:red;font-weight:900;position: absolute;margin-top: -93px;">Price:</div>
<div style="position: absolute;margin-top: -68px;"><asp:Label ID="Price" runat="server" Text='<%# Eval("Price") %>' /></div>
</td>
<asp:Label ID="lblID" runat="server" Text='<%#Eval("CartID") %>' Visible="False" />
<td>
<div >

<div class="col-md-offset-2 col-md-10">
<div >
<asp:Button runat="server" Text="Remove Item" CssClass="btn btn-default" Style="background-color :#CF2929;" OnClick="Unnamed1_Click1" />
<asp:Button runat="server" Text="Buy Now" CssClass="btn btn-default" Style="background-color :#FD9729;" OnClick="Unnamed2_Click1" />
</div>

</div>
</div>
</td>
</tr>

</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

</div> 

My cart code-behind page 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Microsoft.AspNet.Identity;
namespace EFWebApplication1
{
public partial class MyCart : System.Web.UI.Page
{
public string CartID;

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindRepeater();
}

}
private void BindRepeater()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = DAL.ViewDataContext.SqlConnection;

var userId = User.Identity.GetUserId();
SqlCommand cmd = new SqlCommand();
try
{
con.Open();
cmd = new SqlCommand("ViewCartDetails", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@UserID", userId));
SqlDataAdapter sda = new SqlDataAdapter(cmd);
//cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
sda.Fill(dt);
rptCustomers.DataSource = dt;
rptCustomers.DataBind();
if (dt.Rows.Count>0)
{
Label2.Text = "Total Items: " + dt.Rows[0]["ItemCount"].ToString();
Label1.Text = "Total Price: " + dt.Rows[0]["TotalPrice"].ToString();
}


}
catch (SqlException ex)
{
Response.Write("<script>alert('" + ex + "')</script>");
Response.Write(ex);
}
}

protected void rptCustomers_ItemCommand(object source, RepeaterCommandEventArgs e)
{

}

protected void Unnamed1_Click1(object sender, EventArgs e)
{
//string msg = "Item Removed From the Cart";
//Response.Write("<script>alert('" + msg + "')</script>");

var btn = (Button)sender;
//Get the repeater selected row
var item = (RepeaterItem)btn.NamingContainer;
//FInd the control from row
var crtID = ((Label)item.FindControl("lblID")).Text;
CartID = crtID;
DeleteItem();
Response.Redirect("MyCart.aspx");

}
protected void Unnamed2_Click1(object sender, EventArgs e)
{
string msg = "Thank you for buying this Item ";
Response.Write("<script>alert('" + msg + "')</script>");
var btn = (Button)sender;
//Get the repeater selected row
var item = (RepeaterItem)btn.NamingContainer;
//FInd the control from row
var crtID = ((Label)item.FindControl("lblID")).Text;
CartID = crtID;
DeleteItem();
Response.Redirect("MyCart.aspx");

}
private void DeleteItem()
{

SqlConnection con = new SqlConnection();
con.ConnectionString = DAL.ViewDataContext.SqlConnection;
con.Open();
SqlCommand cmd = new SqlCommand();
try
{
SqlCommand myCmd = new SqlCommand("DeleteCartItem", con);
myCmd.CommandType = CommandType.StoredProcedure;
myCmd.Parameters.Add(new SqlParameter("@CartID", CartID));
myCmd.ExecuteNonQuery();

con.Close();
string msg = "Item Removerd From the Cart";
Response.Write("<script>alert('" + msg + "')</script>");

}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex + "')</script>");
Response.Write(ex);
}
}
}
}

this is the Home page image slider

<div class="w3-content w3-section" style="max-width:500px">
<img class="mySlides" src="Slideshow/B0.jpg" style="width:100%">
<img class="mySlides" src="Slideshow/B1.jpg" style="width:100%">
<img class="mySlides" src="Slideshow/B2.jpg" style="width:100%">
<img class="mySlides" src="Slideshow/B3.jpg" style="width:100%">
<img class="mySlides" src="Slideshow/B4.jpg" style="width:100%">
<img class="mySlides" src="Slideshow/B5.jpg" style="width:100%">
<img class="mySlides" src="Slideshow/B6.jpg" style="width:100%">
<img class="mySlides" src="Slideshow/B7.jpg" style="width:100%">
<img class="mySlides" src="Slideshow/B8.jpg" style="width:100%">
<img class="mySlides" src="Slideshow/B9.jpg" style="width:100%">

</div>
<script>
var myIndex = 0;
carousel();

function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) { myIndex = 1 }
x[myIndex - 1].style.display = "block";
setTimeout(carousel, 2000); // Change image every 2 seconds
}
</script> 

You need to create stored procedures inside your database.

 





You can download the complete project.

 

Comments

Post a Comment