.net的建站步骤(官网实例)
2015-12-25 15:12
357 查看
代码特色:
EntityFrameworkCodeFirst
CodeFirst是EntityFramework4.1后新增的一种映射方式
,在这种方式下,开发人员只需要编写代码,由ORM框架自动动创建模型和数据库
数据库则可看作类似于XML一样序列化的方式,非常简洁(由于开发人员可以无需关心数据库的具体结构,最初也有叫做CodeOnly的)。
EntityFrameworkCodeFirst
试了下安装不成功:
提示针对的解决方案框架不符合。
而在2011四月发布的EntityFramework4中存在三种工作方式,他们分别为:CodeFirst,ModelFirst和DatabaseFirst
DataAnnotations数据注释
Stronglytypeddatacontrols强类型数据控制
Modelbinding模型绑定
可以学到:
Whatyou'lllearn:
Howtocreateashoppingcartforthewebapplication.
Howtoenableuserstoadditemstotheshoppingcart.
HowtoaddaGridViewcontroltodisplayshoppingcartdetails.
Howtocalculateanddisplaytheordertotal.
Howtoremoveandupdateitemsintheshoppingcart.
Howtoincludeashoppingcartcounter.
1,给网页应用创建购物车
2,让用户给购物车增加项目
3,增加GridView控件来显示购物车详细资料
4,计算和显示订单总数
5,移除和更新购物车中的项目
6,引入购物车数量
创建购物车
之前,增加网页和代码从数据库中查看产品数据。
本次,将创建购物车来管理用户感兴趣的产品。即使用户没有注册和登录,也能浏览并向购物车增加项目。
管理购物车访问,用户第一次访问购物车的时候,将使用agloballyuniqueidentifier(GUID)给用户分配一个独立的ID。你会使用ASP.NET会话状态(Sessionstate)存储此ID。
注意:ASP.NET会话状态是一个存储用户特定信息的方便的地方,当用户离开网站的时候将会失效。当误用sessionstate,将会使得大型网站性能受到影响。使用会话状态的轻应用效果良好。本例程展示了没有外部提供者时,怎样使用sessionstate。会话状态存储在托管网站的Web服务器的在内部进程中。
大型网站提供多个应用实例,或者在不同的服务器上运行一个应用的多个实例、考虑使用WindowsAzureCacheService
这个缓冲服务提供一种分布式缓冲服务,是一种外部到网站的分布式缓存服务并解决使用内部进程sessionstate。
Formoreinformationsee,HowtoUseASP.NETSessionStatewithWindowsAzureWebSites.
然而,代码通过使用数据注释属性
你将要增加的购物车逻辑,将包含管理一下行为的能力:
1,向购物车中增加项目。
2,从购物车中移除项目。
3,获取购物车id。
4,获取购物车中的项目。
5,计算购物车项目的总量。
6,更新购物车数据。
购物车网页(ShoppingCart.aspx)和购物车类将一起使用来访问购物车中的数据。(ShoppingCart.aspx)网页将显示用户所有的项目到购物车中。除了购物车网页和类,你将创建一个(AddToCart.aspx)网页来向购物车中增加产品。你也将向该网页(ShoppingCart.aspx),和ProductList.aspx网页中增加代码来提供一个到AddToCart.aspx页的链接,以便用户可以增加产品到购物车中。
Thefollowingdiagramshowsthebasicprocessthatoccurswhentheuseraddsaproducttotheshoppingcart.
下面的代码展示了当用户向购物车中增加产品时发生的基本过程。
当用户点击了ProductList.aspx页的,或者ProductDetails.aspx页的AddToCart链接,应用将会导航到AddToCart.aspx页,并自动到ShoppingCart.aspx页。AddToCart.aspx页会通过调用ShoppingCart类中的方法增加向购物车中选择产品,
ShoppingCart.aspx页将显示已经加入到购物车中的产品。
NamethenewfolderLogic
InSolutionExplorer,right-clicktheWingtipToysprojectandselectAdd->NewFolder.NamethenewfolderLogic.
Right-clicktheLogicfolderandthenselectAdd->NewItem.
AddanewclassfilenamedShoppingCartActions.cs.
Replacethedefaultcodewiththefollowingcode:
AddToCart方法使得独立的产品可以包括在基于产品id的购物车中。产品被加入到车中,或者如果车已经包含了一个那个产品的项目,数量得到增长。
AddToCart.aspx页将期望有一个产品id传给它。该产品id将在调用
注:你将为该页调整后端代码(AddToCart.aspx.cs),而不是pageUI(AddToCart.aspx).
TheAddNewItem
dialogboxisdisplayed.
Addastandardnewpage(Web
Form)totheapplicationnamedAddToCart.aspx.
·InSolutionExplorer,right-clicktheAddToCart.aspx
pageandthenclickViewCode.TheAddToCart.aspx.cscode-behind
fileisopenedintheeditor.
·ReplacetheexistingcodeintheAddToCart.aspx.cs
code-behindwiththefollowing:
当AddToCart.aspx页加载后,产品id从查询字符串中被获取。下一步,一个购物车类的实例被创建且被用来调用之前例子中加入的
之前提到的,一个用户id被用来辨别被分配到特定用户的产品。这个id被增加到
thattheuserhasaddedtotheirshoppingcart.显示用户增加到车中的产品。Itwillalsoprovidetheabilitytoadd,removeandupdateitemsin
theshoppingcart.也提供增加,删除,更新车中项目的能力。
InSolutionExplorer,
right-clickWingtipToys,
clickAdd
->NewItem.
TheAddNewItem
dialogboxisdisplayed.
Addanewpage(WebForm)
thatincludesamasterpagebyselectingWebFormusingMasterPage.NamethenewpageShoppingCart.aspx.
SelectSite.Mastertoattachthe
masterpagetothenewlycreated.aspxpage.
IntheShoppingCart.aspx
page,replacetheexistingmarkupwiththefollowingmarkup:
TheShoppingCart.aspxpageincludesaGridViewcontrol
named
ShoppingCart.aspx页包含
一个GridView控件。
Thiscontrolusesmodelbindingtobindtheshoppingcart
datafromthedatabasetotheGridViewcontrol.
该控件使用模板绑定来将购物车数据从数据库绑定到GridView控件。
Whenyousetthe
propertyoftheGridView
control,thedata-bindingexpression
markupofthecontrolandthecontrolbecomesstronglytyped.
当你设置了GridView控件的
Asmentionedearlier
inthistutorialseries,youcanselectdetailsofthe
usingIntelliSense.
之前例子中提到的,有可以使用IntelliSense选详细的项目对象。
Toconfigureadatacontroltousemodelbindingtoselect
data,yousetthe
使用模型绑定来选择数据来配置数据控件,
Inthemarkupabove,yousetthe
tousetheGetShoppingCartItemsmethodwhichreturnsalistof
objects.
在上面的标记中,使用GetShoppingCartItems方法设置了
TheGridViewdatacontrolcallsthemethodattheappropriate
timeinthepagelifecycleandautomaticallybindsthereturneddata.
GridView数据控件在网页的生命周期内的合适的时间调用该方法,且自动绑定返回的数据。
The
added.
code-behindtoretrieveandpopulatetheShoppingCartUI.
InSolutionExplorer,
right-clicktheShoppingCart.aspxpageandthenclickViewCode.TheShoppingCart.aspx.cs
code-behindfileisopenedintheeditor.
Replacetheexistingcode
withthefollowing:
Asmentionedabove,the
callsthe
thepagelifecycleandautomaticallybindsthereturneddata.
前面提到,
The
methodcreatesaninstanceofthe
Then,thecodeusesthatinstancetoreturntheitemsin
thecartbycallingthe
然后,代码使用实例通过
AddingProductsto
WheneithertheProductList.aspxortheProductDetails.aspx
pageisdisplayed,theuserwillbeabletoaddtheproducttotheshopping
cartusingalink.
当不管ProductList.aspx
显示还是ProductDetails.aspx显示,用户将能使用链接增加产品到购物车中。
Whentheyclickthelink,theapplicationnavigatestothe
processingpagenamedAddToCart.aspx.
当他们点击链接,应用导航到名为AddToCart.aspx的进程页。
TheAddToCart.aspxpagewillcallthe
methodinthe
tutorial.AddToCart.aspx页将调用
Now,you’lladdanAddtoCartlinktoboththeProductList.aspx
pageandtheProductDetails.aspxpage.
现在,你将增加一个AddtoCart链接,到ProductList.aspx和ProductDetails.aspx页中。
Thislinkwill
includetheproduct
链接将包括用来从数据库中获取数据的产品id
。
InSolutionExplorer,find
andopenthepagenamedProductList.aspx.
Addthemarkuphighlightedin
yellowtotheProductList.aspxpagesothattheentirepageappears
asfollows:
shoppingcart.
PressF5toruntheapplication.
Aftertheprojectrecreatesthedatabase,thebrowserwillopenandshow
theDefault.aspxpage.
项目重新创建数据库后,浏览器将打开并且显示Default.aspx页。
SelectCarsfromthecategory
navigationmenu.
TheProductList.aspxpageisdisplayedshowingonlyproducts
includedinthe“Cars”category.
从种类category导航菜单中选择车。ProductList.aspx页显示仅仅包含“Cars”category的产品。
Click
theAddtoCart
linknexttothefirstproductlisted(theconvertiblecar).
TheShoppingCart.aspxpageisdisplayed,showingtheselectioninyour
shoppingcart.
显示ShoppingCart.aspx页,在购物车中展示了选择的项目。
ViewadditionalproductsbyselectingPlanesfromthecategory
navigationmenu.
ClicktheAddtoCartlinknexttothefirstproductlisted.
TheShoppingCart.aspxpageisdisplayedwiththeadditionalitem.
Closethebrowser.
又选了一个Planes项目到购物车中。
willadda
anddisplaythetotalorderamountintheshoppingcartpage.
除了增加购物车中的产品,还将在购物车
InSolutionExplorer,open
theShoppingCartActions.csfileintheLogicfolder.
Addthefollowing
First,the
shoppingcartfortheuser.
首先,
Thenthemethodgetsthecarttotalbymultiplyingthe
productpricebytheproductquantityforeachproductlistedinthecart.
然后,
Note
Theabovecodeusesthenullabletype“
Nullabletypescanrepresentallthevaluesofanunderlyingtype,andalsoas
anullvalue.Formoreinformationsee,UsingNullable
Types
上面代码使用nullabletype“
pagetocallthe
pagewhenthepageloads.
接下来,将修改ShoppingCart.aspx页的代码,来调用
InSolutionExplorer,
right-clicktheShoppingCart.aspxpageandselectViewCode.
IntheShoppingCart.aspx.cs
file,updatethe
WhentheShoppingCart.aspxpageloads,itloadsthe
shoppingcartobjectandthenretrievestheshoppingcarttotalbycallingthe
methodofthe
messagetothateffectisdisplayed.
producttotheshoppingcart,butyoucanseetheshoppingcarttotal.
运行应用,你不仅能增加一个产品到购物车中,但是你能看到购物车总数。
PressF5toruntheapplication.
ThebrowserwillopenandshowtheDefault.aspxpage.
SelectCarsfromthecategory
navigationmenu.
ClicktheAddToCartlinknextto
thefirstproduct.
TheShoppingCart.aspxpage
isdisplayedwiththeordertotal.显示订单数量。
·Addsomeotherproducts(forexample,a
plane)tothecart.
·TheShoppingCart.aspxpage
isdisplayedwithanupdatedtotalforalltheproductsyou'veadded.
Stoptherunningappbyclosingthebrowserwindow.
anUpdate
buttonandaCheckout
buttontotheshoppingcartpage.TheCheckoutbuttonisnotuseduntil
laterinthistutorialseries.
为了允许用户修改购物车,你将增加一个更新按钮和校验按钮到购物车页。Checkout按钮到后面才使用。
InSolutionExplorer,open
theShoppingCart.aspxpageintherootofthewebapplication
project.
ToaddtheUpdatebuttonandtheCheckoutbuttontotheShoppingCart.aspx
page,addthemarkuphighlightedinyellowtotheexistingmarkup,as
showninthefollowingcode:
Whentheuser
clickstheUpdatebutton,theUpdateBtn_Click
eventhandlerwillbecalled.Thiseventhandlerwillcallthecodethatyou’ll
addinthenextstep.
当用户点击了Update后,UpdateBtn_Click事件触发将被调用。这个事件处理将调用你接下来加入的代码。
Next,youcan
updatethecodecontainedintheShoppingCart.aspx.csfiletoloop
throughthecartitemsandcalltheRemoveItemand
UpdateItemmethods.
接下来,你能更新包含在ShoppingCart.aspx.cs文件中的代码,调用RemoveItem和UpdateItem方法。
InSolutionExplorer,open
theShoppingCart.aspx.csfileintherootofthewebapplication
project.
Addthefollowingcodesections
highlightedinyellowtotheShoppingCart.aspx.csfile:
WhentheuserclickstheUpdatebuttonontheShoppingCart.aspx
page,theUpdateCartItemsmethodiscalled.
用户点了ShoppingCart.aspx页上的Update后,UpdateCartItems方法被调用。
TheUpdateCartItemsmethodgetstheupdatedvaluesforeach
itemintheshoppingcart.
UpdateCartItems方法为购物车中的每个项目获得了更新值。
Then,the
UpdateCartItemsmethodcallsthe
(addedandexplainedinthenextstep)toeitheraddorremoveitemsfromthe
shoppingcart.
然后,UpdateCartItems方法调用
Oncethedatabase
hasbeenupdatedtoreflecttheupdatestotheshoppingcart,theGridViewcontrol
isupdatedontheshoppingcartpagebycallingthe
methodfortheGridView.
一旦数据库被更新,反应更新到购物车,GridView控件通过GridView
Also,thetotal
orderamountontheshoppingcartpageisupdatedtoreflecttheupdatedlist
ofitems.
购物车页中的总订单数量被更新反应到项目更新列表中。
havebeenaddedforupdatingthequantityofanitemandremovinganitem.Now,
addthecodethatwillmakethesecontrolswork.
ShoppingCart.aspx页中,你可以看到控件已经加入来更新项目数量和移除一个项目。现在,增加代码来让这些控件工作。
InSolutionExplorer,open
theShoppingCartActions.csfileintheLogicfolder.
Addthefollowingcode
highlightedinyellowtotheShoppingCartActions.csclassfile:
The
fromthe
page,containsthelogictoeitherupdateorremoveitemsfromtheshopping
cart.
The
methoditeratesthroughalltherowswithintheshoppingcartlist.
Ifashoppingcartitemhasbeenmarkedtoberemoved,or
thequantityislessthanone,the
如果购物车项目已经标记为移除,或数量少于一个,
Otherwise,theshoppingcartitemischeckedforupdates
whenthe
否则,购物车项目被验证
Aftertheshoppingcartitemhasbeenremovedorupdated,
thedatabasechangesaresaved.
购物车项目移除或更新之后,数据库改变被保存。
The
holdalltheshoppingcartitems.
The
needtobeupdatedorremoved.
Inthenexttutorial,youwillusethe
methodtocleartheshoppingcartafterpurchasingproducts.
下一个例子中,你将在购买完产品后使用
Butfornow,you
willusethe
filetodeterminehowmanyitemsareintheshoppingcart.
但现在,你将使用
shoppingcart,youwilladdacountertotheSite.Masterpage.This
counterwillalsoactasalinktotheshoppingcart.
允许用户查看购物车中项目的总数,你将向Site.Master页中增加计数。这个计数也将作为一个到购物车中的链接。
InSolutionExplorer,open
theSite.Masterpage.
Modifythemarkupbyadding
theshoppingcartcounterlinkasshowninyellowtothenavigation
sectionsoitappearsasfollows:
BeforethepageisrenderedasHTML,the
eventisraised.
在网页被渲染为HTML之前,
Inthe
oftheshoppingcartisdeterminedbycallingthe
Thereturnedvalueisaddedtothe
spanincludedinthemarkupoftheSite.Masterpage.
返回值被增加到
The
tagsenablestheinnerelementstobeproperlyrendered.Whenanypageofthe
siteisdisplayed,theshoppingcarttotalwillbedisplayed.
Theusercanalso
clicktheshoppingcarttotaltodisplaytheshoppingcart.
用户也可以点击购物车总数来显示购物车。
Testing
theCompletedShoppingCart
Youcanrunthe
applicationnowtoseehowyoucanadd,delete,andupdateitemsinthe
shoppingcart.Theshoppingcarttotalwillreflectthetotalcostofallitems
intheshoppingcart.
PressF5torunthe
application.
ThebrowseropensandshowstheDefault.aspxpage.
SelectCarsfromthe
categorynavigationmenu.
ClicktheAddToCartlink
nexttothefirstproduct.
TheShoppingCart.aspxpageisdisplayedwiththeordertotal.
SelectPlanesfromthe
categorynavigationmenu.
ClicktheAddToCartlink
nexttothefirstproduct.
Setthequantityofthefirstitem
intheshoppingcartto3andselecttheRemoveItemcheckboxof
theseconditem.
ClicktheUpdatebuttonto
updatetheshoppingcartpageanddisplaythenewordertotal.
WingtipToysWebFormssampleapplication.Duringthistutorialyouhaveused
EntityFrameworkCodeFirst,dataannotations,stronglytypeddatacontrols,
andmodelbinding.
Theshoppingcartsupportsadding,deleting,andupdating
itemsthattheuserhasselectedforpurchase.Inadditiontoimplementingthe
shoppingcartfunctionality,youhavelearnedhowtodisplayshoppingcart
itemsinaGridView
controlandcalculatetheordertotal.
总结
这个例子中,你已经为WebForms例子应用创建了一个购物车。本次已经使用了EntityFrameworkCodeFirst,数据注释,强类型数据控件,模型绑定。
购物车支持增加,删,更新用户选择购买的项目。除了实现购物车功能,你已经学到怎样在GridView控件中显示购物车项目,并计算订单总数。
EntityFrameworkCodeFirst
CodeFirst是EntityFramework4.1后新增的一种映射方式
,在这种方式下,开发人员只需要编写代码,由ORM框架自动动创建模型和数据库
数据库则可看作类似于XML一样序列化的方式,非常简洁(由于开发人员可以无需关心数据库的具体结构,最初也有叫做CodeOnly的)。
EntityFrameworkCodeFirst
试了下安装不成功:
提示针对的解决方案框架不符合。
而在2011四月发布的EntityFramework4中存在三种工作方式,他们分别为:CodeFirst,ModelFirst和DatabaseFirst
DataAnnotations数据注释
Stronglytypeddatacontrols强类型数据控制
Modelbinding模型绑定
可以学到:
Whatyou'lllearn:
Howtocreateashoppingcartforthewebapplication.
Howtoenableuserstoadditemstotheshoppingcart.
Howtoadda
Howtocalculateanddisplaytheordertotal.
Howtoremoveandupdateitemsintheshoppingcart.
Howtoincludeashoppingcartcounter.
1,给网页应用创建购物车
2,让用户给购物车增加项目
3,增加GridView控件来显示购物车详细资料
4,计算和显示订单总数
5,移除和更新购物车中的项目
6,引入购物车数量
创建购物车
之前,增加网页和代码从数据库中查看产品数据。
本次,将创建购物车来管理用户感兴趣的产品。即使用户没有注册和登录,也能浏览并向购物车增加项目。
管理购物车访问,用户第一次访问购物车的时候,将使用agloballyuniqueidentifier(GUID)给用户分配一个独立的ID。你会使用ASP.NET会话状态(Sessionstate)存储此ID。
注意:ASP.NET会话状态是一个存储用户特定信息的方便的地方,当用户离开网站的时候将会失效。当误用sessionstate,将会使得大型网站性能受到影响。使用会话状态的轻应用效果良好。本例程展示了没有外部提供者时,怎样使用sessionstate。会话状态存储在托管网站的Web服务器的在内部进程中。
大型网站提供多个应用实例,或者在不同的服务器上运行一个应用的多个实例、考虑使用WindowsAzureCacheService
这个缓冲服务提供一种分布式缓冲服务,是一种外部到网站的分布式缓存服务并解决使用内部进程sessionstate。
Formoreinformationsee,
AddCartItemasaModelClass
之前的例子,通过在Models文件夹中创建了Category和
Product两个类,给category和product数据定义了图式(schema)。现在,增加一个类给购物车定义图式。后面,你将增加一个类来处理对
CartItem表的数据访问。这个类将会增加对购物车中项目的增加、移除、更新。
CartItem类包含图式,用来定义每个产品的用户添加到购物车。这个图式与之前例子中的图式相似。按惯例,EntityFrameworkCodeFirst期望
CartItem表的主键是CartItemId或
ID。
然而,代码通过使用数据注释属性
[Key]重写了默认行为。ItemId属性的
[Key]属性指定了
ItemID属性为主键。CartId属性指定了用户的id,用以分配来购买东西。当用户访问购物车时,你将增加代码来创建用户id。
这个id也将被存储为ASP.NETSession变量。
UpdatetheProductContext
除了增加CartItem类,你会需要更新数据库内容类来管理实体类和提供对数据库的数据访问,做到这些,你将增加新创建的CartItem模型类到产品内容类中。
像之前实例中提到的那样,ProductContext文件中的代码增加了
System.Data.Entity命名空间以便你能访问EntityFramework的所有核心功能。功能包括通过使用强类型对象查询、插入、更新、删除数据的能力。
ProductContext类增加了对新建的CartItem类的访问。
ManagingtheShoppingCartBusinessLogic
下一步,你将在一个新的逻辑文件夹中创建ShoppingCart类。ShoppingCart类处理对CartItem表的数据访问。CartItem类也将包括增加、移除、更新购物车中项目的业务逻辑。你将要增加的购物车逻辑,将包含管理一下行为的能力:
1,向购物车中增加项目。
2,从购物车中移除项目。
3,获取购物车id。
4,获取购物车中的项目。
5,计算购物车项目的总量。
6,更新购物车数据。
购物车网页(ShoppingCart.aspx)和购物车类将一起使用来访问购物车中的数据。(ShoppingCart.aspx)网页将显示用户所有的项目到购物车中。除了购物车网页和类,你将创建一个(AddToCart.aspx)网页来向购物车中增加产品。你也将向该网页(ShoppingCart.aspx),和ProductList.aspx网页中增加代码来提供一个到AddToCart.aspx页的链接,以便用户可以增加产品到购物车中。
Thefollowingdiagramshowsthebasicprocessthatoccurswhentheuseraddsaproducttotheshoppingcart.
下面的代码展示了当用户向购物车中增加产品时发生的基本过程。
当用户点击了ProductList.aspx页的,或者ProductDetails.aspx页的AddToCart链接,应用将会导航到AddToCart.aspx页,并自动到ShoppingCart.aspx页。AddToCart.aspx页会通过调用ShoppingCart类中的方法增加向购物车中选择产品,
ShoppingCart.aspx页将显示已经加入到购物车中的产品。
CreatingtheShoppingCartClass
购物车类将增加到应用中的分文件夹以便将在model(Modelsfolder)和pages(rootfolder)及logic(Logicfolder)之间有一个明显的区分。NamethenewfolderLogic
InSolutionExplorer,right-clicktheWingtipToysprojectandselectAdd->NewFolder.NamethenewfolderLogic.
Right-clicktheLogicfolderandthenselectAdd->NewItem.
AddanewclassfilenamedShoppingCartActions.cs.
Replacethedefaultcodewiththefollowingcode:
AddToCart方法使得独立的产品可以包括在基于产品id的购物车中。产品被加入到车中,或者如果车已经包含了一个那个产品的项目,数量得到增长。
GetCartId
方法为用户返回车的id号。车id用于跟踪一个用户在他们购物车中的项目。如果用户没有存在的车id,一个新的车id会为他们创建。如果用户用注册的用户名登录,车id被设置为他们的用户名。然而,如果用户没有登录,车id被设置为一个独有的值(一个GUID)。GUID保证基于session,只为每个用户创建一个车号。
GetCartItems
方法为用户返回一个购物车项目列表。该例子的后面,你将会看到模型绑定被用来在购物车中通过GetCartItems方法显示购物车项目
CreatingtheAdd-To-CartFunctionality
之前提到的,你将创建一个进程页命名为AddToCart.aspx,用来为用户向购物车中增加新的产品。该网页将调用刚刚创建的ShoppingCart
类中的
AddToCart
方法。
AddToCart.aspx页将期望有一个产品id传给它。该产品id将在调用
ShoppingCart类中的
AddToCart
方法的时候被使用。
注:你将为该页调整后端代码(AddToCart.aspx.cs),而不是pageUI(AddToCart.aspx).
TocreatetheAdd-To-Cartfunctionality:
InSolutionExplorer,right-clicktheWingtipToysproject,clickAdd->NewItem.TheAddNewItem
dialogboxisdisplayed.
Addastandardnewpage(Web
Form)totheapplicationnamedAddToCart.aspx.
·InSolutionExplorer,right-clicktheAddToCart.aspx
pageandthenclickViewCode.TheAddToCart.aspx.cscode-behind
fileisopenedintheeditor.
·ReplacetheexistingcodeintheAddToCart.aspx.cs
code-behindwiththefollowing:
当AddToCart.aspx页加载后,产品id从查询字符串中被获取。下一步,一个购物车类的实例被创建且被用来调用之前例子中加入的
AddToCart
方法。AddToCart方法包含在ShoppingCartActions.cs文件中,包括增加选择产品到购物车或增加选择的产品数量的逻辑。如果产品没有被加入到购物车中,产品被增加到数据库的
CartItem
表中。如果产品已经加入到购物车中,且用户增加了相同产品的多余的项目,CartItem表中的产品数量会增加。最后,该页重定向到ShoppingCart.aspx页,这样你将在下一步增加,用户看到一个在购物车中更新的项目列表。
之前提到的,一个用户id被用来辨别被分配到特定用户的产品。这个id被增加到
CartItem表中的一行,每次用户增加一个产品到购物车中。
CreatingtheShoppingCartUI
TheShoppingCart.aspxpagewilldisplaytheproductsthattheuserhasaddedtotheirshoppingcart.显示用户增加到车中的产品。Itwillalsoprovidetheabilitytoadd,removeandupdateitemsin
theshoppingcart.也提供增加,删除,更新车中项目的能力。
InSolutionExplorer,
right-clickWingtipToys,
clickAdd
->NewItem.
TheAddNewItem
dialogboxisdisplayed.
Addanewpage(WebForm)
thatincludesamasterpagebyselectingWebFormusingMasterPage.NamethenewpageShoppingCart.aspx.
SelectSite.Mastertoattachthe
masterpagetothenewlycreated.aspxpage.
IntheShoppingCart.aspx
page,replacetheexistingmarkupwiththefollowingmarkup:
TheShoppingCart.aspxpageincludesaGridViewcontrol
named
CartList.
ShoppingCart.aspx页包含
一个GridView控件。
Thiscontrolusesmodelbindingtobindtheshoppingcart
datafromthedatabasetotheGridViewcontrol.
该控件使用模板绑定来将购物车数据从数据库绑定到GridView控件。
Whenyousetthe
ItemType
propertyoftheGridView
control,thedata-bindingexpression
Itemisavailableinthe
markupofthecontrolandthecontrolbecomesstronglytyped.
当你设置了GridView控件的
ItemType属性,控件标记的数据绑定表达式项目是可用的,且控件成为强类型对象。
Asmentionedearlier
inthistutorialseries,youcanselectdetailsofthe
Itemobject
usingIntelliSense.
之前例子中提到的,有可以使用IntelliSense选详细的项目对象。
Toconfigureadatacontroltousemodelbindingtoselect
data,yousetthe
SelectMethodpropertyofthecontrol.
使用模型绑定来选择数据来配置数据控件,
要设置控件的SelectMethod属性。
Inthemarkupabove,yousetthe
SelectMethod
tousetheGetShoppingCartItemsmethodwhichreturnsalistof
CartItem
objects.
在上面的标记中,使用GetShoppingCartItems方法设置了
SelectMethod方法,返回一个CartItem对象的列表。
TheGridViewdatacontrolcallsthemethodattheappropriate
timeinthepagelifecycleandautomaticallybindsthereturneddata.
GridView数据控件在网页的生命周期内的合适的时间调用该方法,且自动绑定返回的数据。
The
GetShoppingCartItemsmethodmuststillbe
added.
GetShoppingCartItems方法必须增加。
RetrievingtheShoppingCartItems
Next,youaddcodetotheShoppingCart.aspx.cscode-behindtoretrieveandpopulatetheShoppingCartUI.
向ShoppingCart.aspx.cs
中加入代码获取并填充购物车UI.
InSolutionExplorer,
right-clicktheShoppingCart.aspxpageandthenclickViewCode.TheShoppingCart.aspx.cs
code-behindfileisopenedintheeditor.
Replacetheexistingcode
withthefollowing:
Asmentionedabove,the
GridViewdatacontrol
callsthe
GetShoppingCartItemsmethodattheappropriatetimein
thepagelifecycleandautomaticallybindsthereturneddata.
前面提到,
GridView控件自动调用GetShoppingCartItems方法获取返回的数据。
The
GetShoppingCartItems
methodcreatesaninstanceofthe
ShoppingCartActionsobject.
GetShoppingCartItems方法创建了一个ShoppingCartActions对象的实例。
Then,thecodeusesthatinstancetoreturntheitemsin
thecartbycallingthe
GetCartItemsmethod.
然后,代码使用实例通过
GetCartItems方法来返回车中的项目。
AddingProductsto
theShoppingCart
WheneithertheProductList.aspxortheProductDetails.aspxpageisdisplayed,theuserwillbeabletoaddtheproducttotheshopping
cartusingalink.
当不管ProductList.aspx
显示还是ProductDetails.aspx显示,用户将能使用链接增加产品到购物车中。
Whentheyclickthelink,theapplicationnavigatestothe
processingpagenamedAddToCart.aspx.
当他们点击链接,应用导航到名为AddToCart.aspx的进程页。
TheAddToCart.aspxpagewillcallthe
AddToCart
methodinthe
ShoppingCartclassthatyouaddedearlierinthis
tutorial.AddToCart.aspx页将调用
ShoppingCart类中的
AddToCart方法,
Now,you’lladdanAddtoCartlinktoboththeProductList.aspx
pageandtheProductDetails.aspxpage.
现在,你将增加一个AddtoCart链接,到ProductList.aspx和ProductDetails.aspx页中。
Thislinkwill
includetheproduct
IDthatisretrievedfromthedatabase.
链接将包括用来从数据库中获取数据的产品id
。
InSolutionExplorer,find
andopenthepagenamedProductList.aspx.
Addthemarkuphighlightedin
yellowtotheProductList.aspxpagesothattheentirepageappears
asfollows:
TestingtheShoppingCart
Runtheapplicationtoseehowyouaddproductstotheshoppingcart.
PressF5toruntheapplication.
Aftertheprojectrecreatesthedatabase,thebrowserwillopenandshow
theDefault.aspxpage.
项目重新创建数据库后,浏览器将打开并且显示Default.aspx页。
SelectCarsfromthecategory
navigationmenu.
TheProductList.aspxpageisdisplayedshowingonlyproducts
includedinthe“Cars”category.
从种类category导航菜单中选择车。ProductList.aspx页显示仅仅包含“Cars”category的产品。
Click
theAddtoCart
linknexttothefirstproductlisted(theconvertiblecar).
TheShoppingCart.aspxpageisdisplayed,showingtheselectioninyour
shoppingcart.
显示ShoppingCart.aspx页,在购物车中展示了选择的项目。
ViewadditionalproductsbyselectingPlanesfromthecategory
navigationmenu.
ClicktheAddtoCartlinknexttothefirstproductlisted.
TheShoppingCart.aspxpageisdisplayedwiththeadditionalitem.
Closethebrowser.
又选了一个Planes项目到购物车中。
CalculatingandDisplayingtheOrderTotal
Inadditiontoaddingproductstotheshoppingcart,youwilladda
GetTotalmethodtothe
ShoppingCartclass
anddisplaythetotalorderamountintheshoppingcartpage.
除了增加购物车中的产品,还将在购物车
ShoppingCart类中增加
GetTotal方法,并显示购物车页中的总得订单数量。
InSolutionExplorer,open
theShoppingCartActions.csfileintheLogicfolder.
Addthefollowing
GetTotalmethodhighlightedinyellowtothe
ShoppingCartclass,sothattheclassappearsasfollows:
First,the
GetTotalmethodgetstheIDofthe
shoppingcartfortheuser.
首先,
GetTotal方法为用户获取购物车的id。
Thenthemethodgetsthecarttotalbymultiplyingthe
productpricebytheproductquantityforeachproductlistedinthecart.
然后,
GetTotal方法对于购物车中的每个产品列表,通过产品价格乘以产品数量获得车的总数。
Note
Theabovecodeusesthenullabletype“
int?”.
Nullabletypescanrepresentallthevaluesofanunderlyingtype,andalsoas
anullvalue.Formoreinformationsee,UsingNullable
Types
上面代码使用nullabletype“
int?”。空类型能表示所有基础类型的值。也作为一个空值。
ModifytheShoppingCartDisplay
Nextyou’llmodifythecodefortheShoppingCart.aspxpagetocallthe
GetTotalmethodanddisplaythattotalontheShoppingCart.aspx
pagewhenthepageloads.
接下来,将修改ShoppingCart.aspx页的代码,来调用
GetTotal方法并当页面加载时显示ShoppingCart.aspx页中的总数。代码写到Page_Load方法中。
InSolutionExplorer,
right-clicktheShoppingCart.aspxpageandselectViewCode.
IntheShoppingCart.aspx.cs
file,updatethe
Page_Loadhandlerbyaddingthefollowingcodehighlightedinyellow:
WhentheShoppingCart.aspxpageloads,itloadsthe
shoppingcartobjectandthenretrievestheshoppingcarttotalbycallingthe
GetTotal
methodofthe
ShoppingCartclass.Iftheshoppingcartisempty,a
messagetothateffectisdisplayed.
TestingtheShoppingCartTotal
Runtheapplicationnowtoseehowyoucannotonlyaddaproducttotheshoppingcart,butyoucanseetheshoppingcarttotal.
运行应用,你不仅能增加一个产品到购物车中,但是你能看到购物车总数。
PressF5toruntheapplication.
ThebrowserwillopenandshowtheDefault.aspxpage.
SelectCarsfromthecategory
navigationmenu.
ClicktheAddToCartlinknextto
thefirstproduct.
TheShoppingCart.aspxpage
isdisplayedwiththeordertotal.显示订单数量。
·Addsomeotherproducts(forexample,a
plane)tothecart.
·TheShoppingCart.aspxpage
isdisplayedwithanupdatedtotalforalltheproductsyou'veadded.
Stoptherunningappbyclosingthebrowserwindow.
AddingUpdateandCheckoutButtonstotheShoppingCart
Toallowtheuserstomodifytheshoppingcart,you’lladdanUpdate
buttonandaCheckout
buttontotheshoppingcartpage.TheCheckoutbuttonisnotuseduntil
laterinthistutorialseries.
为了允许用户修改购物车,你将增加一个更新按钮和校验按钮到购物车页。Checkout按钮到后面才使用。
InSolutionExplorer,open
theShoppingCart.aspxpageintherootofthewebapplication
project.
ToaddtheUpdatebuttonandtheCheckoutbuttontotheShoppingCart.aspx
page,addthemarkuphighlightedinyellowtotheexistingmarkup,as
showninthefollowingcode:
Whentheuser
clickstheUpdatebutton,theUpdateBtn_Click
eventhandlerwillbecalled.Thiseventhandlerwillcallthecodethatyou’ll
addinthenextstep.
当用户点击了Update后,UpdateBtn_Click事件触发将被调用。这个事件处理将调用你接下来加入的代码。
Next,youcan
updatethecodecontainedintheShoppingCart.aspx.csfiletoloop
throughthecartitemsandcalltheRemoveItemand
UpdateItemmethods.
接下来,你能更新包含在ShoppingCart.aspx.cs文件中的代码,调用RemoveItem和UpdateItem方法。
InSolutionExplorer,open
theShoppingCart.aspx.csfileintherootofthewebapplication
project.
Addthefollowingcodesections
highlightedinyellowtotheShoppingCart.aspx.csfile:
WhentheuserclickstheUpdatebuttonontheShoppingCart.aspx
page,theUpdateCartItemsmethodiscalled.
用户点了ShoppingCart.aspx页上的Update后,UpdateCartItems方法被调用。
TheUpdateCartItemsmethodgetstheupdatedvaluesforeach
itemintheshoppingcart.
UpdateCartItems方法为购物车中的每个项目获得了更新值。
Then,the
UpdateCartItemsmethodcallsthe
UpdateShoppingCartDatabasemethod
(addedandexplainedinthenextstep)toeitheraddorremoveitemsfromthe
shoppingcart.
然后,UpdateCartItems方法调用
UpdateShoppingCartDatabase方法。用于增加或删除项目。
Oncethedatabase
hasbeenupdatedtoreflecttheupdatestotheshoppingcart,theGridViewcontrol
isupdatedontheshoppingcartpagebycallingthe
DataBind
methodfortheGridView.
一旦数据库被更新,反应更新到购物车,GridView控件通过GridView
的DataBind方法更新购物页。
Also,thetotal
orderamountontheshoppingcartpageisupdatedtoreflecttheupdatedlist
ofitems.
购物车页中的总订单数量被更新反应到项目更新列表中。
UpdatingandRemovingShoppingCartItems
OntheShoppingCart.aspxpage,youcanseecontrolshavebeenaddedforupdatingthequantityofanitemandremovinganitem.Now,
addthecodethatwillmakethesecontrolswork.
ShoppingCart.aspx页中,你可以看到控件已经加入来更新项目数量和移除一个项目。现在,增加代码来让这些控件工作。
InSolutionExplorer,open
theShoppingCartActions.csfileintheLogicfolder.
Addthefollowingcode
highlightedinyellowtotheShoppingCartActions.csclassfile:
The
UpdateShoppingCartDatabasemethod,called
fromthe
UpdateCartItemsmethodontheShoppingCart.aspx.cs
page,containsthelogictoeitherupdateorremoveitemsfromtheshopping
cart.
UpdateShoppingCartDatabase方法,调用ShoppingCart.aspx.cs页中的
UpdateCartItems方法,包含更新或移除的逻辑。
The
UpdateShoppingCartDatabase
methoditeratesthroughalltherowswithintheshoppingcartlist.
UpdateShoppingCartDatabase方法迭代购物车清单中的行。
Ifashoppingcartitemhasbeenmarkedtoberemoved,or
thequantityislessthanone,the
RemoveItemmethodiscalled.
如果购物车项目已经标记为移除,或数量少于一个,
RemoveItem方法被调用。
Otherwise,theshoppingcartitemischeckedforupdates
whenthe
UpdateItemmethodiscalled.
否则,购物车项目被验证
UpdateItem方法被调用的时候来更新。
Aftertheshoppingcartitemhasbeenremovedorupdated,
thedatabasechangesaresaved.
购物车项目移除或更新之后,数据库改变被保存。
The
ShoppingCartUpdatesstructureisusedto
holdalltheshoppingcartitems.
ShoppingCartUpdates结构用来控制所有的购物车项目。
The
UpdateShoppingCartDatabasemethodusesthe
ShoppingCartUpdatesstructuretodetermineifanyoftheitems
needtobeupdatedorremoved.
UpdateShoppingCartDatabase方法使用ShoppingCartUpdates结构来决定是否任意的项目需要更新或者移除。
Inthenexttutorial,youwillusethe
EmptyCart
methodtocleartheshoppingcartafterpurchasingproducts.
下一个例子中,你将在购买完产品后使用
EmptyCart方法来清除购物车。
Butfornow,you
willusethe
GetCountmethodthatyoujustaddedtotheShoppingCartActions.cs
filetodeterminehowmanyitemsareintheshoppingcart.
但现在,你将使用
GetCount方法,仅增加ShoppingCartActions.cs文件来决定购物车中有多少项目。
AddingaShoppingCartCounter
Toallowtheusertoviewthetotalnumberofitemsintheshoppingcart,youwilladdacountertotheSite.Masterpage.This
counterwillalsoactasalinktotheshoppingcart.
允许用户查看购物车中项目的总数,你将向Site.Master页中增加计数。这个计数也将作为一个到购物车中的链接。
InSolutionExplorer,open
theSite.Masterpage.
Modifythemarkupbyadding
theshoppingcartcounterlinkasshowninyellowtothenavigation
sectionsoitappearsasfollows:
BeforethepageisrenderedasHTML,the
Page_PreRender
eventisraised.
在网页被渲染为HTML之前,
Page_PreRender事件被唤起。
Inthe
Page_PreRenderhandler,thetotalcount
oftheshoppingcartisdeterminedbycallingthe
GetCountmethod.
在Page_PreRender处理程序中,购物车总数通过GetCount方法决定。
Thereturnedvalueisaddedtothe
cartCount
spanincludedinthemarkupoftheSite.Masterpage.
返回值被增加到
cartCountspan中。
包括Site.Master页的标记。
The
<span>
tagsenablestheinnerelementstobeproperlyrendered.Whenanypageofthe
siteisdisplayed,theshoppingcarttotalwillbedisplayed.
<span>标记使得内部元素被合理的表达。当任意的网页显示,购物车总数将希纳斯。
Theusercanalso
clicktheshoppingcarttotaltodisplaytheshoppingcart.
用户也可以点击购物车总数来显示购物车。
Testing
theCompletedShoppingCart
Youcanrunthe
applicationnowtoseehowyoucanadd,delete,andupdateitemsinthe
shoppingcart.Theshoppingcarttotalwillreflectthetotalcostofallitems
intheshoppingcart.
PressF5torunthe
application.
ThebrowseropensandshowstheDefault.aspxpage.
SelectCarsfromthe
categorynavigationmenu.
ClicktheAddToCartlink
nexttothefirstproduct.
TheShoppingCart.aspxpageisdisplayedwiththeordertotal.
SelectPlanesfromthe
categorynavigationmenu.
ClicktheAddToCartlink
nexttothefirstproduct.
Setthequantityofthefirstitem
intheshoppingcartto3andselecttheRemoveItemcheckboxof
theseconditem.
ClicktheUpdatebuttonto
updatetheshoppingcartpageanddisplaythenewordertotal.
Summary
Inthistutorial,youhavecreatedashoppingcartfortheWingtipToysWebFormssampleapplication.Duringthistutorialyouhaveused
EntityFrameworkCodeFirst,dataannotations,stronglytypeddatacontrols,
andmodelbinding.
Theshoppingcartsupportsadding,deleting,andupdating
itemsthattheuserhasselectedforpurchase.Inadditiontoimplementingthe
shoppingcartfunctionality,youhavelearnedhowtodisplayshoppingcart
itemsinaGridView
controlandcalculatetheordertotal.
总结
这个例子中,你已经为WebForms例子应用创建了一个购物车。本次已经使用了EntityFrameworkCodeFirst,数据注释,强类型数据控件,模型绑定。
购物车支持增加,删,更新用户选择购买的项目。除了实现购物车功能,你已经学到怎样在GridView控件中显示购物车项目,并计算订单总数。
CheckoutandPaymentwithPayPal
校验和付款。相关文章推荐
- c# 提取word文件中的图片问题
- spring 事务传播问题
- The type or namespace name 'Bitmap' could not be found (are you missing a using directive or an asse
- Home+work
- hdu 3449 Consumer(依赖背包)
- asp.net dataset 判断是否为空
- 欢迎使用CSDN-markdown编辑器
- 《Effective java》读书记录-第3条-用私有构造器或者枚举类型强化Singleton属性
- MP4文件格式详解——结构概述
- 定制单元格tableViewcell和表视图编辑模式---摘自培训文档
- CSS 笔记一(Selectors/ Backgrounds/ Borders/ Margins/ Padding/ Height and Width)
- 版本更改
- C# asp.net 操作Word的前提配置和简单的方法
- oc基础总结二 线程和进程
- Xcode7 通过 Single View Application 得到一个 Empty Application 工程
- 前端工程师应该注意的一些细节,面试容易问到
- java文件下载的文件名乱码问题的解决
- mongodb3.0的权限认证问题
- 详解WordPress中提醒安装插件以及隐藏插件的功能实现
- 函数模板与类模板的简单实例