Build a Shopping Cart by use C# work in asp.net—end in this post

Now to create Products page, add a new webform and name it Products.aspx, add sqldataSource and configure it for select statement,
Add a DataList Control on the page and make SqlDataSource1 it’s source.
Configure Datalist according to below mentioned source

<form id=”form1″ runat=”server”>

<asp:ScriptManager ID=”ScriptManager1″ runat=”server” />

<div>

<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”

ConnectionString=”<%$ ConnectionStrings:ConnectionString %>”

SelectCommand=”SELECT [ProductID], [Name], [Description],

[Price], [ImageUrl] FROM [Products]“>

</asp:SqlDataSource>

</div>

 

<asp:DataList ID=”DataList1″ runat=”server”

DataSourceID=”SqlDataSource1″

RepeatColumns=”4″

RepeatDirection=”Horizontal”>

<ItemTemplate>

<asp:ImageButton ID=”ImageButton1″ runat=”server”

ImageUrl=’<%# Eval(“ImageUrl”, “Images\\thumb_{0}”) %>’

PostBackUrl=’<%# Eval(“ProductID”,

“ProductDetails.aspx?ProductID={0}”) %>’ />

<br />

<asp:Label ID=”NameLabel” runat=”server”

Text=’<%# Eval(“Name”) %>’>

</asp:Label>

<asp:Label ID=”PriceLabel” runat=”server”

Text=’<%# Eval(“Price”, “{0:C}”) %>’>

</asp:Label><br />

<br />

<br />

</ItemTemplate>

</asp:DataList><br />

<asp:HyperLink ID=”CartLink” runat=”server”

NavigateUrl=”~/UserCart.aspx”>

View Shopping Cart

</asp:HyperLink><br />

</form>
Now add a new webform and name it ProductDetails.aspx , this page is used for showing details for selected product from product catalog page, again add a SqlDataSource and DataList Control on this page and configure them according to source shown below, this time datalist is populated using QueryString Parameters.

<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”

ConnectionString=”<%$ ConnectionStrings:ConnectionString %>”

SelectCommand=”SELECT [ProductID], [Name], [Description],

[Price], [ImageUrl] FROM [Products]

WHERE ([ProductID] = @ProductID)”>

<SelectParameters>

<asp:QueryStringParameter Name=”ProductID”

QueryStringField=”ProductID”

Type=”Decimal” />

</SelectParameters>

</asp:SqlDataSource>

</div>

 

<asp:DataList ID=”DataList1″ runat=”server”

DataSourceID=”SqlDataSource1″>

<ItemTemplate>

<asp:Image ID=”Image1″ runat=”server”

ImageUrl=’<%# Eval(“ImageUrl”,”~/Images\\{0}”) %>’/>

<asp:Label ID=”ImageUrlLabel” runat=”server”

Text=’<%# Eval(“ImageUrl”) %>’

Visible=”False”>

</asp:Label><br />

<asp:Label ID=”NameLabel” runat=”server”

Text=’<%# Eval(“Name”) %>’>

</asp:Label><br />

<asp:Label ID=”DescriptionLabel” runat=”server”

Text=’<%# Eval(“Description”) %>’>

</asp:Label><br />

<asp:Label ID=”PriceLabel” runat=”server”

Text=’<%# Eval(“Price”, “{0:##0.00}” ) %>’>

</asp:Label><br />

</ItemTemplate>

</asp:DataList><br />

<asp:Button ID=”btnAdd” runat=”server” OnClick=”Button1_Click”

Text=”Add to Cart” /><br /><br />

<asp:HyperLink ID=”HyperLink1″ runat=”server”

NavigateUrl=”~/Products.aspx”>

Return to Products Page

</asp:HyperLink>

Write this code in C# code behind of ProductDetails.aspx page

protected void Button1_Click(object sender, EventArgs e)

{

double Price = double.Parse(((Label)

DataList1.Controls[0].FindControl(“PriceLabel”)).Text);

string ProductName = ((Label)

DataList1.Controls[0].FindControl(“NameLabel”)).Text;

string ProductImageUrl = ((Label)

DataList1.Controls[0].FindControl(“ImageUrlLabel”)).Text;

int ProductID = int.Parse(Request.QueryString["ProductID"]);

if (Profile.SCart == null)

{

Profile.SCart = new ShoppingCartExample.Cart();

}

Profile.SCart.Insert

(ProductID, Price, 1, ProductName, ProductImageUrl);

Server.Transfer(“Products.aspx”);

}
Now right click on solution explorer and add new web user control, name it CartControl.ascx
In design view of this control add a new GridView control and a label below gridview, html shource of this control should look like this

<%@ Control Language=”C#” AutoEventWireup=”true”

CodeFile=”CartControl.ascx.cs”

Inherits=”CartControl” %>

<asp:GridView ID=”grdCart” runat=”server”

AutoGenerateColumns=”False”

DataKeyNames=”ProductID”

OnRowCancelingEdit=”grdCart_RowCancelingEdit”

OnRowDeleting=”grdCart_RowDeleting”

OnRowEditing=”grdCart_RowEditing”

OnRowUpdating=”grdCart_RowUpdating”>

<Columns>

<asp:TemplateField>

<ItemTemplate>

<asp:Image ID=”Image1″ runat=”server”

ImageUrl=’<%#Eval(“ImageUrl”,”~/Images/thumb_{0}”)%>’/>

</ItemTemplate>

</asp:TemplateField>

<asp:BoundField DataField=”ProductName”

HeaderText=”Product” ReadOnly=”True”/>

<asp:BoundField DataField=”Quantity” HeaderText=”Quantity”/>

<asp:BoundField DataField=”Price” DataFormatString=”{0:c}”

HeaderText=”Price” ReadOnly=”True” />

<asp:BoundField DataField=”SubTotal” DataFormatString=”{0:c}”

HeaderText=”Total” ReadOnly=”True” />

<asp:CommandField ShowDeleteButton=”True”

ShowEditButton=”True”/>

</Columns>

<EmptyDataTemplate>

Your Shopping Cart is empty, add items

<a href=”Products.aspx”>Add Products</a>

</EmptyDataTemplate>

</asp:GridView>

<asp:Label ID=”TotalLabel” runat=”server”></asp:Label>
Open web.config file and add this section for enabling anonymous users to add items to cart

<system.web>

<authorization>

<allow users=”?” />

<allow roles=”admin” />

</authorization>

<roleManager enabled=”true” />

<authentication mode=”Forms” />

<compilation debug=”true”>

</compilation>

</system.web>

<system.web>

<anonymousIdentification enabled=”true”/>

<profile enabled=”true”>

<properties>

<add name=”SCart” serializeAs=”Binary”

type=”ShoppingCartExample.Cart”

allowAnonymous=”true”/>

</properties>

</profile>

</system.web>
Now go to code behnd of CartControl.ascx and write this code

protected void Page_Load(object sender, EventArgs e)

{

if (Profile.SCart == null)

{

Profile.SCart = new ShoppingCartExample.Cart();

}

if (!Page.IsPostBack)

{

ReBindGrid();

}

if(Profile.SCart.Items == null)

{

TotalLabel.Visible = false;

}

}

protected void grdCart_RowEditing

(object sender, GridViewEditEventArgs e)

{

grdCart.EditIndex = e.NewEditIndex;

ReBindGrid();

}

protected void grdCart_RowUpdating

(object sender, GridViewUpdateEventArgs e)

{

TextBox txtQuantity = (TextBox)

grdCart.Rows[e.RowIndex].Cells[2].Controls[0];

int Quantity = Convert.ToInt32(txtQuantity.Text);

if (Quantity == 0)

{

Profile.SCart.Items.RemoveAt(e.RowIndex);

}

else

{

Profile.SCart.Items[e.RowIndex].Quantity

= Quantity;

}

grdCart.EditIndex = -1;

ReBindGrid();

}

protected void grdCart_RowCancelingEdit

(object sender, GridViewCancelEditEventArgs e)

{

grdCart.EditIndex = -1;

ReBindGrid();

}

protected void grdCart_RowDeleting

(object sender, GridViewDeleteEventArgs e)

{

Profile.SCart.Items.RemoveAt(e.RowIndex);

ReBindGrid();

}

private void ReBindGrid()

{

grdCart.DataSource = Profile.SCart.Items;

DataBind();

TotalLabel.Text = string.Format(“Total:{0,19:C}”,

Profile.SCart.Total);

}
Now add Global Application Class (Global.asax) by right clicking on solution explorer > add new Item. and write code mentioned below in it.

01void Profile_OnMigrateAnonymous(object sender, ProfileMigrateEventArgs e)

02    {

03        ProfileCommon anonymousProfile = Profile.GetProfile(e.AnonymousID);

04        if (anonymousProfile.SCart != null)

05        {

06            if (Profile.SCart == null)

07                Profile.SCart = new ShoppingCartExample.Cart();

08

09            Profile.SCart.Items.AddRange(anonymousProfile.SCart.Items);

10

11            anonymousProfile.SCart = null;

12        }

13

14        ProfileManager.DeleteProfile(e.AnonymousID);

15        AnonymousIdentificationModule.ClearAnonymousIdentifier();

16    }

17

Add another webform and name it UserCart.aspx, in design view of this page drag the CartControl we’ve just created and put a hyperlink for going back to products cataloge page

Tha’s it , build and run the application
Have fun

 

Build a Shopping Cart by use C# work in asp.net—continue

Recently studying Java in UTS , It remind me that really like c# I just learned in TAFE.

Previous I create a shopping cart table in my database then use c# to add,update,delete the products in my shopping cart table into my database.

But know I have better solution,just by create a Shopping Cart Class,

here is it the Shopping Cart Class:(ShoppingCart.cs)

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections.Generic;

namespace ShoppingCartExample
{
    [Serializable] 
    public class CartItem
    {
        private int _productID;
        private string _productName;
        private string _imageUrl;
        private int _quantity;
        private double _price;
        private double _subTotal;

        public CartItem()
        { 
        }
        public CartItem(int ProductID, string ProductName, string ImageUrl, int Quantity, double Price)
        {
            _productID = ProductID;
            _productName = ProductName;
            _imageUrl = ImageUrl;
            _quantity = Quantity;
            _price = Price;
            _subTotal = Quantity * Price;

        }
        public int ProductID
        {
            get
            {
                return _productID;
            }
            set
            {
                _productID = value;
            }
        }

         public string ProductName
         {
            get { return _productName; }
            set { _productName = value; }
         }

         public string ImageUrl
         {
             get { return _imageUrl; }
             set { _imageUrl = value; }
         }

         public int Quantity
         {
             get { return _quantity; }
             set { _quantity = value; }
         }

         public double Price
         {
             get { return _price; }
             set { _price = value; }
         }

         public double SubTotal
         {
             get { return _quantity * _price; }
            
         }
     
    }
    [Serializable]
    public class Cart
    {
        private DateTime _dateCreated;
        private DateTime _lastUpdate;
        private List _items;

        public Cart()
        {
            if (this._items == null)
            {
                this._items = new List();
                this._dateCreated = DateTime.Now;
            }
        }

        public List Items
        {
 		get { return _items;}
		set { _items = value;}
	    }

        public void Insert(int ProductID, double Price, int Quantity, string ProductName, string ImageUrl)
        {
            int ItemIndex = ItemIndexOfID(ProductID);
            if (ItemIndex == -1)
            {
                CartItem NewItem = new CartItem();
                NewItem.ProductID = ProductID;
                NewItem.Quantity = Quantity;
                NewItem.Price = Price;
                NewItem.ProductName = ProductName;
                NewItem.ImageUrl = ImageUrl;
                _items.Add(NewItem);
            }
            else
            {
                _items[ItemIndex].Quantity += 1;
            }
            _lastUpdate = DateTime.Now;
        }

        public void Update(int RowID, int ProductID, int Quantity, double Price)
        {
            CartItem Item = _items[RowID];
            Item.ProductID = ProductID;
            Item.Quantity = Quantity;
            Item.Price = Price;
            _lastUpdate = DateTime.Now;
        }

        public void DeleteItem(int rowID)
        {
            _items.RemoveAt(rowID);
            _lastUpdate = DateTime.Now;
        }

        private int ItemIndexOfID(int ProductID)
        {
            int index = 0;
            foreach (CartItem item in _items)
            {
                if (item.ProductID == ProductID)
                {
                    return index;
                }
                index += 1;
            }
            return -1;
        }

        public double Total
        {
            get
            {
                double t = 0;
                if (_items == null)
                {
                    return 0;
                }
                foreach (CartItem Item in _items)
                {
                    t += Item.SubTotal;
                }
                return t;
            }
        }
 
    }
}


How to access a use control from another user control in asp.net,C#

I recently need work with sitefinity CMS system website. I need create a page have left sidebar images url equal to my left side dropdown list value.So I create two user controls and left sidebar user control and right content user control. Then I have problems to solve just let my left sidebar user control to access my right sidebar user control. Here is my solution, see the link below for how it work.

http://www.royaletravel.com.au/package-book?p=Romantic-Getaway-Premium

First, I create a user control is PackageBookingForm.ascx, and on the back code I create this
//make get this dropdown list value


public DropDownList Experience_DDL
{
get
{
return this.DropDownList_experience;
}
}

Second, I create another user control, called Image_package_sidebar.ascx, because I need access PackageBookingForm.ascx control’s dropdown list value, here is the very important to put reference on the top of this control,here is <%@ Reference VirtualPath=”youpath/PackageBookingForm.ascx” %>, then write the code on the back end.


PackageBookingForm ctrlP = (PackageBookingForm)Page.FindControl("yourcontrolID");
DropDownList ddl = ctrlP.Experience_DDL;
Image_package_sidebar.ImageUrl = "~/yourpath/" + ddl.SelectedValue + ".jpg";

then put those control in the same page, the left sidebar control will access your right user control dropdown list value

Revision:how to use backbone

three way to create your  model:

Person = Backbone.Model.extend({})
Person = Backbone.Model.extend({
defaults:{
name:"";//Model arrow undefined data
create:new Date() //here arrow put PHP function
}
});
Person = Backbone.Model.extend({
defaults:function(){
return   {  name:"";  //Model arrow undefined data
create:new Date()
}
}
});

Read and Write:

var person = new Person({ name:”Sandy”,age:”12″});

person.get(“name”);//” Sandy”

person.set({name:”Anna”,age:”12″});//overwrite it

Create Simple View

PersonView = Backbone.View.extend({

render:function(){

var person = “<p>” + this.model.get(“user”) + “</p>”;

$(this.el).html(person);

}

});

“this.el” meaning: every View Model create a Page Scope, el means the root tag<div></div>,

Get Model data Add into HTML page

var personView = new PersonView({

model:person;

})

personView.render();

console.log(personView.el);//check the el

Get Data from the server(RESTful way)

var Person = Backbone.Model.extend({urlRoot:”/person”}); //point to the data sourse

var person = new Person({id:1}); //point to your object

person.fetch();//get /person/1

person.save();//put /person/1

var newPerson=new PersonModel(); //create a new object

newPerson.set({name:”Sandy Zhang”}); // give the an name

newPerson.save(); // insert into /person

newPerson.get(“id”); //2

newPerson.destroy();// Delete /person/2

Create Better View

var PersonView = Backbone.View.extend({

tagName:”article”,

id:”personOne”;

class:”person”,

attributes:{title:this.model.get(“name”)},

render:function(){

var person=”<p>” + this.model.get(“name”)+”</p>”;

$(this.el).html(person);

}

});

this will render html sourse:

<article id=”personOne” class = “person” title=”Sandy Zhang”>

<p>Sandy Zhang</p>

</article>

Cache of the jQuery object

$(“#personOne”).html();

in Backbone.js: $(this.el).html(); or better way : this.$el.html()

el  is  generated for the cache of jQuery object, so that it can be used repeatedly without fear of generating multiple instances of the jQuery object.

Built-in template engine(underscore template)

use render() seems not elegant ,now we use underscore template

var PersonView = Backbone.View.extend({

tagName:”article”,

id:”personOne”;

class:”person”,

attributes:{title:this.model.get(“name”)},

template: _.template(‘<p><%= name %></p>’),

render:function(){

data = this.model.toJSON();

$(this.el).html(template(data));

}

}); // Cool! looking better

Track your instance

var person = new Person({name:”sandy”}); //create a instance

person.on(“change”,function(){

alert(“Something changed on ” + this.get(“name”) );

});

person.on(“change:age”,function(){

alert(this.get(“name”) +”,Your age has been changed ”  );

});

Change data to JSON format

var person = new Person({id:1});

console.log(person.toJSON());

//or

console.log(JSON.stringify(person));

Now Add View event

var PersonView = Backbone.View.extend({

tagName:”article”,

id:”personOne”;

class:”person”,

attributes:{title:this.model.get(“name”)},

template: _.template(‘<p><%= name %></p>’),

render:function(){

data = this.model.toJSON();

this.$el.html(template(data));

},

events:{ “mouseover” :”showMore”,},

showMore:function(){…….},

});

Advance Level

1.Server <= (get) model (data) => view (rendering) => DOM

var PersonView = Backbone.View.extend({

input:_.template(‘<input type=”text”><%= name%></input>’),

submit: _.template(‘<button type=”submit”>Change Name</button>’),

render: function(){

data = this.model.toJSON();

this.$el.html(input(data)).html(submit);

}

});

Now we can  change name now, the question is how do you know the model data has changed? This needs to view it through the event.

var PersonView = Backbone.View.extend({

events:{“submit button”:”updateName”}

updataName:function(){

newName = $(this).val();  // this=button!

if(newName !== this.model.get(‘name’)){

this.model.set({name:newName}); }

else{ return;}

}

});

Well…it did work, but the problem is : should belong Model processing logic  put in the View now. So we reconstruct it.

var PersonView = Backbone.View.extend({

events:{“submit button”:”updateName”}

updateName:function(){

newName = $(this).val();

this.model.updateName(newName);

}

});

var Person = Backbone.Model.extend({

updateName: function(newName){

this.set({name:newName});

this.save(); // tell server to save the new name into database

}

})

2.The above, we pass the parameter value changes transferred to the Model, and then further processed by the Model it wants to do.

Now, the loop model like this:

Server <= (updated) model (proceed) <= (notification) view <= (user interaction) DOM

If the data model changes, how to notice the view? You might immediately think of the render method can be performed immediately after the completion notification view:

var PersonView = Backbone.View.extend({

updateName:function(){

newName = $(this).val();

this.model.updateName(newName);

this.render();

}

});

Ah good idea …… but it is not always useful, because the value of the model could be changed elsewhere, such as in another view . So, how to notify the specified view  response to the model changes?

So, use listenTo() function

var PersonView = Backbone.View.extend({

initialize:function(){

this.listenTo(this.model,”change”,this.render);

//this.model.on(“change”,this.render,this);

}

});

3. collection

a)Collect multiple model data

When there was more and more instances , in order to facilitate the processing of them, we usually think of them together with the array. Backbone.js Collection module provides a simplified way to help us:

var Person = Backbone.Collection.extend({ model:person });

var person.add{[{name:"Sandy Zhang", id:1},{name:"Anna li",id:2}]};

person.length //=>2

person.get(2) // => { name : “Anna li”,id:2}

person.at(0) //=>{ name:”Sandy Zhang”, id:1}

HTML5 Push State API

Backbone.history.start({pushState: true});

var App = new (Backbone.Router.extend({
initialize: function() {
this.person = new person();
this.personView = new personView({collection: this.person});
$(“#app”).append(this.personView.el);
},

index: function() {
this.person.fetch();
},

start: function() {
Backbone.history.start({pushState: true});
}
}));

$(function() { App.start(); });

Backbone Collection

run the code in the browse should look like

backbone3

here is the code for get the collection:

<script type=”text/javascript”>
Student = Backbone.Model.extend({
defaults:{
name:””,
age:””
}

});
ClassRoom = Backbone.Collection.extend({
model:Student
});

var student1 = new Student({name:”Sandy”,age:”20″});
var student2 = new Student({name:”Rachel”,age:”18″});
var student3 = new Student({name:”Anna”,age:”23″});
var collection = new ClassRoom([student1,student2,student3]);

</script>

Backbone – Router

On this post create 2 template,and use backbone router to communicate with those 2 pages, here is the code.

<script type=”text/template” id=”first_template”>
<label>My First View:</label>
<a href=”#second”>Go to Second View</a>

</script>

<script type=”text/template” id=”second_template”>
<label>My Second View:</label>
<a href=”#first”>Go to First View</a>

</script>

<div id = “container”></div>

<script type=”text/javascript”>
FirstView = Backbone.View.extend({
el:$(‘#container’),
initialize:function(){
this.render();
},

render:function(){
var template = _.template($(‘#first_template’).html(),{});

this.$el.html(template);

}

});

SecondView = Backbone.View.extend({
el:$(‘#container’),
initialize:function(){
this.render();
},

render:function(){
var template = _.template($(‘#second_template’).html(),{});

this.$el.html(template);

}

});

MyRouter = Backbone.Router.extend({
routes:{
“”:”firstPage”,
“first”:”firstPage”,
“second”:”secondPage”
},

firstPage:function(){
new FirstView();
},
secondPage:function(){
new SecondView();
}

});

var router = new MyRouter();
Backbone.history.start();

</script>

 

Best Web Design, web developer, php developer,designers,freelance

Follow

Get every new post delivered to your Inbox.

Join 85 other followers