您的位置:首页 > 编程语言 > ASP

Building an ASP.NET Shopping Cart Using DataTables

2004-10-20 07:38 423 查看
MostdynamicWebapplicationsarecreatedforthesolepurposeofmakingmoneyontheWeb.

Let'sfaceit:whywouldyougothroughalltheworkofcreatingadynamicWebapplicationifyoudon'tplantomakemoneythroughit?Sure,companiesemploydynamicintranetsitesandtherearestillsome--althoughveryfew--freeWebapplicationsyoucanuse.

Intherealworld,however,dynamicWebapplicationsarecreatedinanattempttomakemoneybyallowingsiteownerstosellmerchandiseontheWeb.ProvidinguserswiththecapabilitytoadditemstoavirtualshoppingcartastheybrowsethroughyourWebsiteisstillverymuchabusinessthatcommandsgoodmoney.CompaniessuchasVeriSign,Paypal,WebAssist,andLinkPointchargetoprovidedeveloperswiththecapabilitytoaddshoppingcartfunctionalitytotheirownWebsites.Butwhypay$300-$400forasolutionthatsomeoneelsealreadybuilt,whenyoucanbuildonejustaseasilyyourselfutilizingnewtechnologyinASP.NET,forfree?

ThisarticlewillallowyoutodevelopandimplementyourownshoppingcartutilizingaSession,aDataGrid,andthe
DataTable
classofthe
DataSet
object.Throughthisarticle,you'lllearnto:

BuildauserinterfaceusingASP.NETWebServerControls
DynamicallyconstructaDataTabledependingonuserinteraction
BindthedynamicallyconstructedDataTabletoaDataGrid
Allowtheusertoremoveitemsfromthecartfreely
Keeparunningcosttotalofitemswithinthecart

Attheendofthisarticle,you'llhaveafullyfunctioningshoppingcart,andyou'llhavegainedathoroughunderstandingofDataTables,DataGrids,andSessionVariables.Downloadacompletedemonstrationofthefinalproducthere.

Thisprojectisseparatedintofiveparts:

Buildingtheuserinterface

BuildingtheDataTablestructure

Addingitemstothecart

Keepingarunningtotal

Removingitemsfromthecart

Step1:BuildingtheShoppingCartUserInterface
TheuserinterfaceorUIfortheapplicationisquitesimple.Infact,mostoftheinteractionwilloccurwithintheDataGrid,buttheUIdoesincludesomekeycomponentsthattheuserwillbeinteractingwith:

A
DropDownList
Webcontrol
thatwilldisplaytheproductsthatwe'lloffer.Thecostofeachitemwillbeassociatedwiththevalueofthe
DropDownList
Webcontrolforsimplicity'ssake.
A
TextBox
Webcontrol
thatofferstheusertheabilitytoadjustquantities
A
Button
Webcontrol
toaddtothecart
A
DataGrid
thatwillcontainthecart'scontents
A
Label
control
thatwilldisplaytotheuserarunningtotalintermsofprice

NowthatyouhaveanideaofwhattheUIwilldisplay,let'saddthesecomponentstothebodyofanHTMLpage.UsingDreamweaverMX,we'llcreateanewpageandaddthiscodeintothe
<body>
tagofthepage:

<formrunat="server">
Product:<br>
<asp:DropDownListid="ddlProducts"runat="server">
<asp:ListItemValue="4.99">Socks</asp:ListItem>
<asp:ListItemValue="34.99">Pants</asp:ListItem>
<asp:ListItemValue="14.99">Shirt</asp:ListItem>
<asp:ListItemValue="12.99">Hat</asp:ListItem>
</asp:DropDownList><br>
Quantity:<br>
<asp:textboxid="txtQuantity"runat="server"/><br><br>
<asp:Buttonid="btnAdd"runat="server"Text="AddToCart"
onClick="AddToCart"/><br><br>
<asp:DataGridid="dg"runat="server"/><br><br>
Total:
<asp:Labelid="lblTotal"runat="server"/>
</form>


Thecodeisactuallyquitesimpleandneedsverylittleexplanation.Basically,ahard-coded
DropDownList
control(
ddlProducts
)
isadded,withfourproducts.Thecostofthoseproductsismaintainedbyassociatingadecimalvalueforeachspecificproduct.

Second,a
TextBox
control(
txtQuantity
)isaddedsothattheusercanmodifyquantities.Next,a
Button
control(
btnAdd
)isaddedwiththetext"AddtoCart".The
onClick
eventassociatedwiththeButtoncontrolwillcallthe
AddToCart()
subroutine,whichwillbecreatedinthenextsection.

Next,a
DataGrid
(
dg
)isaddedwhichwillbeusedtobindtothedynamicallyconstructed
DataTable
.Remember,the
DataTable
willbeconstructedincode,andboundtothe
DataGrid
forpresentationtotheuser.We'lladdabuttoncolumntoallowtheusertoremoveaspecificitemifheorshewishesalittlelater.Finally,we'lladda
Label
control(
lblTotal
),whichwillbeusedtodisplaytotheuserarunningtotaloftheitemswithinthecart.

Step2:Buildingthe
DataTable
Structure

Ifyou'refamiliarwithDataSets
,
thenyouknowthatDataTablesprovideyouwithawaytodynamicallycreateapurelymemory-residentrepresentationofadatabasetable.Typically,you'dfillaDataTable
fromanexistingdatabase,butyoucouldalsocreateoneprogrammatically,aswillbethecasehere.

InaDataTable,columnsarerepresentedbythecolumnsproperty,androwsarerepresentedbytherowsproperty.Thus,DataTableswillbetheperfectchoiceforthecreationofourshoppingcart.Wecanbuildthecolumnsjustaswewouldwithinadatabase,usingthecolumnspropertyofthe
DataTable,andaddrowstotheDataTablewiththe
Rows
property.WiththeDataTablebuilt,wecanthenbindtheDataTabletoaDataGridtodisplaytheresultsinanintuitivemanner.

BecauseDataTablescontainrowsandcolumns,youwillbeabletoeffectivelymockthestructureofaconventionaldatabasetable.TherowswillbeaddedtotheDataTableastheuseraddsitemstothecart.Fornow,we'llneedtoconstructthecolumnsthatwillserveasthecategoriesfortherowitems.Inorderforthecarttofunctioncorrectly,we'llneedtoaddthefollowingcolumnswithacorrespondingdatatype:



You'reprobablywonderinghowdatatypes,autoincrement,anduniquenesswillbesetprogrammatically.Remember,DataTablescontaincolumnandrowproperties.Someofthosepropertiesincludetheabilitytosettheabovementioneditems,justasyouwouldatraditionaldatabasetable.You'llalsonoticethatthe
DataTable
containsacolumnforID.Technically,thiscolumnhasnothingtodowiththeshoppingcart,butitwillhavealottodowithkeepingtheitemsinthecartunique,andwillallowustoestablishaprimarykeyifweeverwanttocreatearelationshipwithanotherDataTable.

FornowwejustwantthestructureoftheDataTablebuiltwhenthepageloadsforthefirsttime.Wedon'twanttoactuallystarttodefinerowsuntiltheuserselectsanitemtoaddtothecart.

Tobeginbuildingthecart'sstructure,addthiscodeintotheheadofyourpage:

<scriptrunat="server">

DimobjDTAsSystem.Data.DataTable
DimobjDRAsSystem.Data.DataRow

PrivateSubPage_Load(sAsObject,eAsEventArgs)
IfNotIsPostBackThen
makeCart()
EndIf
EndSub

FunctionmakeCart()
objDT=NewSystem.Data.DataTable("Cart")
objDT.Columns.Add("ID",GetType(Integer))
objDT.Columns("ID").AutoIncrement=True
objDT.Columns("ID").AutoIncrementSeed=1

objDT.Columns.Add("Quantity",GetType(Integer))
objDT.Columns.Add("Product",GetType(String))
objDT.Columns.Add("Cost",GetType(Decimal))

Session("Cart")=objDT
EndFunction

</script>


Lookingatthecode,youcansee,thatthe
makeCart()
functioniscalledonlywhenthepageisloadedforthefirsttime.ThisisthereasonfortheIsPostBackcheck.

Withinthe
makeCart()
function,we'lladdthecodethatdefinestheactualstructurefortheDataTableanditscolumns.First,weaddacolumntotheDataTablenamed
ID
,assigningitthedatatypeforinteger.Weassignthepropertyfor
AutoIncrement
to
True
,andbegintheseedat1.

Next,addthreemorecolumnstotheDataTablefor
Quantity
,
Product
,and
Cost
,assigningthemthedatatypesforinteger,string,anddecimalrespectively.Finally,theDataTableisaddedintoa
Session
convenientlynamed"
Cart
",forstorage.

That'sit!IfyouthinkaboutthestructureofadatabasetableandthenconsiderthestructureandcodefortheDataTable,theybegintoresembleeachotherconceptually.Thenextstepinvolvesaddingitemstothecart,whichisnoharderthandefiningnewrowsfortheDataTable.

Step3:BuildingtheAddtoCartFunctionality
NowthatthestructureoftheDataTablehasbeencompletelybuilt,we'llwanttobegintoaddtothecartthespecificitemsthattheuserselectsfromthedropdownmenu.Again,todothis,wesimplyconstructnewrowsandaddthemtotheappropriatepositionwithinthe
DataTable
cart.ToconstructtheAddtoCartfunctionality,addthecodebelow:

SubAddToCart(sAsObject,eAsEventArgs)

objDT=Session("Cart")
DimProduct=ddlProducts.SelectedItem.Text

objDR=objDT.NewRow
objDR("Quantity")=txtQuantity.Text
objDR("Product")=ddlProducts.SelectedItem.Text
objDR("Cost")=Decimal.Parse(ddlProducts.SelectedItem.Value)
objDT.Rows.Add(objDR)
Session("Cart")=objDT

dg.DataSource=objDT
dg.DataBind()

EndSub


You'llrememberthattheButtoncontrolhadthe
onClick
eventthatcalledthe
AddToCart()
subroutine.Thissubroutinecontainsallthecodethat'snecessarytoretrieveanexistingcartfromthe
Session
objectifitexists,addnewitemstothecart,placethecartbackintothesession,andfinally,bindtotheDataGrid.

AsImentioned,thefirsttwolinesofcoderetrievethecartfromthesessionifitexists,andretrievetheproductselectedfromthedropdownmenu.Asyouhavealreadycreatedanewinstanceofthe
DataRow
class,youcancreatethenewrowsforthespecificcolumnswithintheDataTable.

You'llnoticethatwesetthe
Quantity
columnequaltothevalueofthequantitytextboxcontrol,andsetthe
Product
columnequaltothetextvalueofthedropdownmenuselection.Wethenconvertthevalueofthedropdownmenu,whichiscost,intoadecimalvalueforthecostcolumn.Finally,weaddthenewrowtotheDataTable,addtheDataTabletotheSession,oroverwriteitifitalreadyexists,andbindtheDataTabletotheDataGrid.

Testwhatyouhavesofarinthebrowser.Itshouldworkfine,exceptforoneproblem.You'llseethatifyouselectanitem,addittothecart,andthenselectthesameitemagain,ratherthanaddingthesumoftheoldquantitywiththenewquantity,itjustcreatesanewrow.Youcanfixthisproblembymodifyingthe
AddToCart()
subroutine.Justbelowthecodewhereyouretrievetheitemfromthedropdownmenu,addthefollowinglooptocheckwithintheDataTableforanexistingproduct:

DimblnMatchAsBoolean=False

ForEachobjDRInobjDT.Rows
IfobjDR("Product")=ProductThen
objDR("Quantity")+=txtQuantity.Text
blnMatch=True
ExitFor
EndIf
Next


Nowwrapthenewcodethataddsanewrowwithinaconditionalstatement.

IfNotblnMatchThen
objDR=objDT.NewRow
objDR("Quantity")=Int32.Parse(txtQuantity.Text)
objDR("Product")=ddlProducts.SelectedItem.Text
objDR("Cost")=Decimal.Parse(ddlProducts.SelectedItem.Value)
objDT.Rows.Add(objDR)
EndIf


Basically,anewrowwillonlybecreatediftheproductisnotfoundwithinthecart.Ifitisfound,however,itwillsimplyadjustthequantitybywhatevertheuserplacesintothequantitytextboxcontrol.

Step4:KeepingtheOrderTotal
Thenextstepwillbetobuildthefunctionthatkeepsarunningtotalofthecostoftheitemswithinthecart.Thiswillbeusedtopresenttheuserwithaworkingtotalastheyaddandremoveitemsinthecart.Youcanaddthisfunctionalityusingthecodebelow:

FunctionGetItemTotal()AsDecimal

DimintCounterAsInteger
DimdecRunningTotalAsDecimal

ForintCounter=0ToobjDT.Rows.Count--1
objDR=objDT.Rows(intCounter)
decRunningTotal+=(objDR("Cost")*objDR("Quantity"))
Next

ReturndecRunningTotal

EndFunction


YoucanseethatthisfunctionsimplyloopsthroughtherowsintheDataTable,multipliesthequantitycolumnbythecostcolumn,andreturnstheresult.Thefirststepinvolvesdefiningthefuncton.Asyouwanttoreturnadecimalvalue,makesureyoudefinethefunctionasadecimal.Next,we'llcreatetwonewvariables:oneasanintegerandoneasadecimal.Next,youloopthroughtherowswithintheDataTableandmultiplythecostcolumnforaspecificrowbythequantityforthatrow,andstoreitwithinthe
decRunningTotal
variable.Finally,we'llreturnthevalue.

Thelaststepwillbetowritethevalueofthefunctionintothelabelcontrol.Addthefollowinglinetotheendofthe
btnAddToCart
subroutine--thiseffectivelywritesthecostintothelabelcontrol:

lblTotal.Text="$"&GetItemTotal()


Saveyourworkandrunitinabrowser.Thistime,asyouadditemstothecart,atotalispresentedwithinthelabelcontrol.Fantastic!Now,thelastpartwe'lldiscussinvolvesremovingitemsfromthecart.

Step5:RemovingItemsfromtheCart
Nowthataworkingmodeloftheshoppingcarthasbeenconstructed,we'llwanttoaddthenextbitoffunctionality:removingitemsfromthecart.Obviouslyyoucanseetheimportanceofthis:youwantuserstobeabletoaddandremoveanyandallitemstoorfromtheshoppingcartasrequired.Addthefunctionalityforremovingitemsfromthecartusingthefollowingsubroutine:

SubDelete_Item(sAsObject,eAsDataGridCommandEventArgs)

objDT=Session("Cart")
objDT.Rows(e.Item.ItemIndex).Delete()
Session("Cart")=objDT

dg.DataSource=objDT
dg.DataBind()

lblTotal.Text="$"&GetItemTotal()

EndSub


Thissubroutine,whichwe'llassociatewiththeDataGridinaminute,simplydumpsthecontentsofthesessionintoanew
DataTable
object,deletesthespecificrowthatauserclicked,andthenplacestherevisedDataTablebackintothe
Session
variableforstorage.Finallywere-bindtotheDataGridandupdatethetotalbycallingthe
GetItemTotal()
function.

You'llwanttonotethatoneoftheparametersbeingpassedintothesubroutineisthatofthe
DataGridCommandEventArgs
.Withoutthisparameter,wewouldn'tbeabletodeterminewhichitemwithintheDataGridtheuserselected.

ThelaststepwillbetomodifytheDataGrid.Youwillneedtoaddanew
button
column,aswellasanewevent,tocallthe
Delete_Item
subroutine.ThenewDataGridshouldresemblethefollowingcode:

<asp:DataGridid=dgrunat="server"ondeletecommand="Delete_Item">
<columns>
<asp:buttoncolumnbuttontype="LinkButton"
commandname="Delete"text="RemoveItem"/>
</columns>
</asp:DataGrid>


Saveyourworkandrunitinthebrowser.Thistimeyoucanaddproductsandremovethemfreely!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: