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
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
A
A
A
A
NowthatyouhaveanideaofwhattheUIwilldisplay,let'saddthesecomponentstothebodyofanHTMLpage.UsingDreamweaverMX,we'llcreateanewpageandaddthiscodeintothe
Thecodeisactuallyquitesimpleandneedsverylittleexplanation.Basically,ahard-coded
Second,a
Next,a
Step2:Buildingthe
Ifyou'refamiliarwithDataSets
InaDataTable,columnsarerepresentedbythecolumnsproperty,androwsarerepresentedbytherowsproperty.Thus,DataTableswillbetheperfectchoiceforthecreationofourshoppingcart.Wecanbuildthecolumnsjustaswewouldwithinadatabase,usingthecolumnspropertyoftheDataTable,andaddrowstotheDataTablewiththe
BecauseDataTablescontainrowsandcolumns,youwillbeabletoeffectivelymockthestructureofaconventionaldatabasetable.TherowswillbeaddedtotheDataTableastheuseraddsitemstothecart.Fornow,we'llneedtoconstructthecolumnsthatwillserveasthecategoriesfortherowitems.Inorderforthecarttofunctioncorrectly,we'llneedtoaddthefollowingcolumnswithacorrespondingdatatype:
You'reprobablywonderinghowdatatypes,autoincrement,anduniquenesswillbesetprogrammatically.Remember,DataTablescontaincolumnandrowproperties.Someofthosepropertiesincludetheabilitytosettheabovementioneditems,justasyouwouldatraditionaldatabasetable.You'llalsonoticethatthe
FornowwejustwantthestructureoftheDataTablebuiltwhenthepageloadsforthefirsttime.Wedon'twanttoactuallystarttodefinerowsuntiltheuserselectsanitemtoaddtothecart.
Tobeginbuildingthecart'sstructure,addthiscodeintotheheadofyourpage:
Lookingatthecode,youcansee,thatthe
Withinthe
Next,addthreemorecolumnstotheDataTablefor
That'sit!IfyouthinkaboutthestructureofadatabasetableandthenconsiderthestructureandcodefortheDataTable,theybegintoresembleeachotherconceptually.Thenextstepinvolvesaddingitemstothecart,whichisnoharderthandefiningnewrowsfortheDataTable.
Step3:BuildingtheAddtoCartFunctionality
NowthatthestructureoftheDataTablehasbeencompletelybuilt,we'llwanttobegintoaddtothecartthespecificitemsthattheuserselectsfromthedropdownmenu.Again,todothis,wesimplyconstructnewrowsandaddthemtotheappropriatepositionwithinthe
You'llrememberthattheButtoncontrolhadthe
AsImentioned,thefirsttwolinesofcoderetrievethecartfromthesessionifitexists,andretrievetheproductselectedfromthedropdownmenu.Asyouhavealreadycreatedanewinstanceofthe
You'llnoticethatwesetthe
Testwhatyouhavesofarinthebrowser.Itshouldworkfine,exceptforoneproblem.You'llseethatifyouselectanitem,addittothecart,andthenselectthesameitemagain,ratherthanaddingthesumoftheoldquantitywiththenewquantity,itjustcreatesanewrow.Youcanfixthisproblembymodifyingthe
Nowwrapthenewcodethataddsanewrowwithinaconditionalstatement.
Basically,anewrowwillonlybecreatediftheproductisnotfoundwithinthecart.Ifitisfound,however,itwillsimplyadjustthequantitybywhatevertheuserplacesintothequantitytextboxcontrol.
Step4:KeepingtheOrderTotal
Thenextstepwillbetobuildthefunctionthatkeepsarunningtotalofthecostoftheitemswithinthecart.Thiswillbeusedtopresenttheuserwithaworkingtotalastheyaddandremoveitemsinthecart.Youcanaddthisfunctionalityusingthecodebelow:
YoucanseethatthisfunctionsimplyloopsthroughtherowsintheDataTable,multipliesthequantitycolumnbythecostcolumn,andreturnstheresult.Thefirststepinvolvesdefiningthefuncton.Asyouwanttoreturnadecimalvalue,makesureyoudefinethefunctionasadecimal.Next,we'llcreatetwonewvariables:oneasanintegerandoneasadecimal.Next,youloopthroughtherowswithintheDataTableandmultiplythecostcolumnforaspecificrowbythequantityforthatrow,andstoreitwithinthe
Thelaststepwillbetowritethevalueofthefunctionintothelabelcontrol.Addthefollowinglinetotheendofthe
Saveyourworkandrunitinabrowser.Thistime,asyouadditemstothecart,atotalispresentedwithinthelabelcontrol.Fantastic!Now,thelastpartwe'lldiscussinvolvesremovingitemsfromthecart.
Step5:RemovingItemsfromtheCart
Nowthataworkingmodeloftheshoppingcarthasbeenconstructed,we'llwanttoaddthenextbitoffunctionality:removingitemsfromthecart.Obviouslyyoucanseetheimportanceofthis:youwantuserstobeabletoaddandremoveanyandallitemstoorfromtheshoppingcartasrequired.Addthefunctionalityforremovingitemsfromthecartusingthefollowingsubroutine:
Thissubroutine,whichwe'llassociatewiththeDataGridinaminute,simplydumpsthecontentsofthesessionintoanew
You'llwanttonotethatoneoftheparametersbeingpassedintothesubroutineisthatofthe
ThelaststepwillbetomodifytheDataGrid.Youwillneedtoaddanew
Saveyourworkandrunitinthebrowser.Thistimeyoucanaddproductsandremovethemfreely!
Let'sfaceit:whywouldyougothroughalltheworkofcreatingadynamicWebapplicationifyoudon'tplantomakemoneythroughit?Sure,companiesemploydynamicintranetsitesandtherearestillsome--althoughveryfew--freeWebapplicationsyoucanuse.
Intherealworld,however,dynamicWebapplicationsarecreatedinanattempttomakemoneybyallowingsiteownerstosellmerchandiseontheWeb.ProvidinguserswiththecapabilitytoadditemstoavirtualshoppingcartastheybrowsethroughyourWebsiteisstillverymuchabusinessthatcommandsgoodmoney.CompaniessuchasVeriSign,Paypal,WebAssist,andLinkPointchargetoprovidedeveloperswiththecapabilitytoaddshoppingcartfunctionalitytotheirownWebsites.Butwhypay$300-$400forasolutionthatsomeoneelsealreadybuilt,whenyoucanbuildonejustaseasilyyourselfutilizingnewtechnologyin
ThisarticlewillallowyoutodevelopandimplementyourownshoppingcartutilizingaSession,aDataGrid,andthe
DataTableclassofthe
DataSetobject.Throughthisarticle,you'lllearnto:
Buildauserinterfaceusing
DynamicallyconstructaDataTabledependingonuserinteraction
BindthedynamicallyconstructedDataTabletoaDataGrid
Allowtheusertoremoveitemsfromthecartfreely
Keeparunningcosttotalofitemswithinthecart
Attheendofthisarticle,you'llhaveafullyfunctioningshoppingcart,andyou'llhavegainedathoroughunderstandingofDataTables,DataGrids,andSessionVariables.
Buildingtheuserinterface
BuildingtheDataTablestructure
Addingitemstothecart
Keepingarunningtotal
Removingitemsfromthecart
Step1:BuildingtheShoppingCartUserInterface
Theuserinterfaceor
A
DropDownListWebcontrolthatwilldisplaytheproductsthatwe'lloffer.Thecostofeachitemwillbeassociatedwiththevalueofthe
DropDownListWebcontrolforsimplicity'ssake.
A
TextBoxWebcontrolthatofferstheusertheabilitytoadjustquantities
A
ButtonWebcontroltoaddtothecart
A
DataGridthatwillcontainthecart'scontents
A
Labelcontrolthatwilldisplaytotheuserarunningtotalintermsofprice
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
DropDownListcontrol(
ddlProducts)isadded,withfourproducts.Thecostofthoseproductsismaintainedbyassociatingadecimalvalueforeachspecificproduct.
Second,a
TextBoxcontrol(
txtQuantity)isaddedsothattheusercanmodifyquantities.Next,a
Buttoncontrol(
btnAdd)isaddedwiththetext"AddtoCart".The
onClickeventassociatedwiththeButtoncontrolwillcallthe
AddToCart()subroutine,whichwillbecreatedinthenextsection.
Next,a
DataGrid(
dg)isaddedwhichwillbeusedtobindtothedynamicallyconstructed
DataTable.Remember,the
DataTablewillbeconstructedincode,andboundtothe
DataGridforpresentationtotheuser.We'lladdabuttoncolumntoallowtheusertoremoveaspecificitemifheorshewishesalittlelater.Finally,we'lladda
Labelcontrol(
lblTotal),whichwillbeusedtodisplaytotheuserarunningtotaloftheitemswithinthecart.
Step2:Buildingthe
DataTableStructure
Ifyou'refamiliarwithDataSets
,thenyouknowthatDataTablesprovideyouwithawaytodynamicallycreateapurelymemory-residentrepresentationofadatabasetable.Typically,you'dfillaDataTablefromanexistingdatabase,butyoucouldalsocreateoneprogrammatically,aswillbethecasehere.
InaDataTable,columnsarerepresentedbythecolumnsproperty,androwsarerepresentedbytherowsproperty.Thus,DataTableswillbetheperfectchoiceforthecreationofourshoppingcart.Wecanbuildthecolumnsjustaswewouldwithinadatabase,usingthecolumnspropertyoftheDataTable,andaddrowstotheDataTablewiththe
Rowsproperty.WiththeDataTablebuilt,wecanthenbindtheDataTabletoaDataGridtodisplaytheresultsinanintuitivemanner.
BecauseDataTablescontainrowsandcolumns,youwillbeabletoeffectivelymockthestructureofaconventionaldatabasetable.TherowswillbeaddedtotheDataTableastheuseraddsitemstothecart.Fornow,we'llneedtoconstructthecolumnsthatwillserveasthecategoriesfortherowitems.Inorderforthecarttofunctioncorrectly,we'llneedtoaddthefollowingcolumnswithacorrespondingdatatype:
You'reprobablywonderinghowdatatypes,autoincrement,anduniquenesswillbesetprogrammatically.Remember,DataTablescontaincolumnandrowproperties.Someofthosepropertiesincludetheabilitytosettheabovementioneditems,justasyouwouldatraditionaldatabasetable.You'llalsonoticethatthe
DataTablecontainsacolumnforID.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
AutoIncrementto
True,andbegintheseedat1.
Next,addthreemorecolumnstotheDataTablefor
Quantity,
Product,and
Cost,assigningthemthedatatypesforinteger,string,anddecimalrespectively.Finally,theDataTableisaddedintoa
Sessionconvenientlynamed"
Cart",forstorage.
That'sit!IfyouthinkaboutthestructureofadatabasetableandthenconsiderthestructureandcodefortheDataTable,theybegintoresembleeachotherconceptually.Thenextstepinvolvesaddingitemstothecart,whichisnoharderthandefiningnewrowsfortheDataTable.
Step3:BuildingtheAddtoCartFunctionality
NowthatthestructureoftheDataTablehasbeencompletelybuilt,we'llwanttobegintoaddtothecartthespecificitemsthattheuserselectsfromthedropdownmenu.Again,todothis,wesimplyconstructnewrowsandaddthemtotheappropriatepositionwithinthe
DataTablecart.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
onClickeventthatcalledthe
AddToCart()subroutine.Thissubroutinecontainsallthecodethat'snecessarytoretrieveanexistingcartfromthe
Sessionobjectifitexists,addnewitemstothecart,placethecartbackintothesession,andfinally,bindtotheDataGrid.
AsImentioned,thefirsttwolinesofcoderetrievethecartfromthesessionifitexists,andretrievetheproductselectedfromthedropdownmenu.Asyouhavealreadycreatedanewinstanceofthe
DataRowclass,youcancreatethenewrowsforthespecificcolumnswithintheDataTable.
You'llnoticethatwesetthe
Quantitycolumnequaltothevalueofthequantitytextboxcontrol,andsetthe
Productcolumnequaltothetextvalueofthedropdownmenuselection.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
decRunningTotalvariable.Finally,we'llreturnthevalue.
Thelaststepwillbetowritethevalueofthefunctionintothelabelcontrol.Addthefollowinglinetotheendofthe
btnAddToCartsubroutine--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
DataTableobject,deletesthespecificrowthatauserclicked,andthenplacestherevisedDataTablebackintothe
Sessionvariableforstorage.Finallywere-bindtotheDataGridandupdatethetotalbycallingthe
GetItemTotal()function.
You'llwanttonotethatoneoftheparametersbeingpassedintothesubroutineisthatofthe
DataGridCommandEventArgs.Withoutthisparameter,wewouldn'tbeabletodeterminewhichitemwithintheDataGridtheuserselected.
ThelaststepwillbetomodifytheDataGrid.Youwillneedtoaddanew
buttoncolumn,aswellasanewevent,tocallthe
Delete_Itemsubroutine.ThenewDataGridshouldresemblethefollowingcode:
<asp:DataGridid=dgrunat="server"ondeletecommand="Delete_Item">
<columns>
<asp:buttoncolumnbuttontype="LinkButton"
commandname="Delete"text="RemoveItem"/>
</columns>
</asp:DataGrid>
Saveyourworkandrunitinthebrowser.Thistimeyoucanaddproductsandremovethemfreely!
相关文章推荐
- Building an AJAX Based Web Chatting Application using ASP.NET 2.0(转载)
- Check/Uncheck all Items in an ASP.NET CheckBox List using jQuery
- Create an Asp.Net Web Forms Application using Bootstrap and Web API
- Building a Real Time ProgressBar using ASP.NET Atlas
- How to generate an RSS feed for your web site using ASP.NET
- Testing an ASP.NET Web Service using PowerShell
- [转]Setting up an ASP.NET website development environment using Visual Studio .NET, Subversion, and Windows XP
- ASP.NET datagrid直接导出为Excel Export to Excel from DataGrid (Using an Microsoft Access database)
- ASP.NET Core Building chat room using WebSocket
- 转载:Using JQuery with an ASP.NET webservice
- How to generate an RSS feed for your web site using ASP.NET
- Integrating OpenID in an ASP.NET MVC Application using DotNetOpenAuth
- Building an ASP.NET Intranet
- Populate an ASP.NET ListBox from JSON results using jQuery
- [收藏]The Baker's Dozen: 13 Tips for Building Database Web Applications Using ASP.NET 3.5, LINQ, and SQL Server 2005 Reporting Services
- [转]An introduction to OAuth 2.0 using Facebook in ASP.NET Core
- Building a Gmail Style File Uploading System using ASP.NET 2.0
- ASP.NET 2.0个性化配置(profile实现shoppingcart) 转..
- How to use an ASP.NET application to query an Indexing Service catalog by using Visual Basic .NET
- How To Create an ASP.NET HTTP Handler by Using Visual C# .NET