电子商务综合设计上机实践三_第1页
电子商务综合设计上机实践三_第2页
电子商务综合设计上机实践三_第3页
电子商务综合设计上机实践三_第4页
电子商务综合设计上机实践三_第5页
已阅读5页,还剩32页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

电子商务综合设计上机实践三一、创建Product表并将其与Department表关联起来。按照上一章创建表的步骤创建Category表。表设计参照如下表格:

屏幕剪辑的捕获时间:2011/9/1816:39二、创建表之间联系(1)在创建了Category表之后,在服务器资源管理器中打开并选中Category表,点击菜单“表设计器”,选择“关系”。(2)、在弹出的对话框中点击“添加”(3)、选择表和列规范,并点击右侧出现的按钮。屏幕剪辑的捕获时间:2011/9/1816:56

(4)在打开的对话框中,将Department设为主键表,将DepartmentID设为两个表的列。(5)点击确定,然后点击关闭保存关系。(6)之后再次按下Ctrl+S再次保存表。此时会出现一个警告信息,提示表Category和Deparment将被更新,要求确认。点击确定。三、添加分类(1)在数据库管理器中打开Category表进行编辑。(2)在Category表中输入数据。(3)现在试着输入一个不存在的门类。在DepartmentID中随便输入一个门类ID,如10,并输入一个目录名称。试着将光标移动到下一行,这时,如果我们前面创建了正确的关系,就会弹出一个错误提示窗口,如下图所示:4、创建Product表并把它与Category建立关联(1)使用前面介绍的步骤,创建一个新的Product表,其字段如下表所示。

屏幕剪辑的捕获时间:2011/9/1821:34创建好的数据表如下图所示:(2)保存出具表并输入Product作为表名。(3)添加几本书籍信息(4)现在让我们为商品和分类创建联接表(在Product和Category之间实现多对多关系)。如下图所示,这个表包括两个字段。(5)选中这两个字段ProductID和CategoryID,然后打开表设计器-〉设置主键。两个金色的钥匙将会出现在左侧,允许为空的复选框自动取消选中。如下图所示。

屏幕剪辑的捕获时间:2011/9/1822:15(6)保存表,并设置表名称为ProductCategory。(7)在服务器资源管理器中展开本例数据库节点,右键点击数据库关系图-〉添加新关系图。之后你将会看见下图所示的弹出的对话框,点击四次添加按钮,把四个表都添加进关系图中,然后点击关闭。

(8)在关系图中自由的放大窗口,并重新排列这些婊,使其适应于屏幕。如果使用默认选项,则你的关系图如下所示:为了起那个之实行在Category表和Product表之间的对对多关系,需要添加两个FOREIGNKEY约束。在本练习中,将可视化地创建这些约束。(9)在ProductCategory表中选中ProductID,点击鼠标左键将其拖到Product表的ProductID列桑,将显示一个添加新的外键关系对话框,并已填入了所需的数据。(10)点击确定按钮添加外间,然后再点击确定按钮关闭外键关系对话框。(11)使用与上一步相同的步骤,在Category和ProductCategory表中的CategoryID列上创建新的关系。现在的关系图已经反映了这些新关系。(12)按Ctrl+S保存关系图和队标所做的改动。当要求输入关系图名称是,输入CatalogDiagram。同时将提示对Product、Category和ProductCategory的修改将被保存到数据库中。点击确定。(13)在数据表ProductCategory中输入数据。五、将以下存储过程添加到BookShop数据库中。

CatalogGetDepartmentDetails当用户在商品目录中选择一个门类是,就需要GetDepartmentDetails存储过程。当这发生时,必须再次查询数据库,找出该门类的名称和描述。这个存储过车把所选的门类ID作为参数,并返回它的名称和描述。在之后创建业务层是,我们将学习如何在执行完存储过程后,把这些值赋给变量。代码如下:CREATEPROCEDURECatalogGetDepartmentDetails(@DepartmentIDINT)ASSELECTName,DescriptionFROMDepartmentWHEREDepartmentID=@DepartmentID

CatalogGetCategoryDetails在访问者选择一个分类并希望找出关于它的详细信息时,将调用该存储过程,它的名称就是功能的描述。代码如下:CREATEPROCEDURECatalogGetCategoryDetails(@CategoryIDINT)ASSELECTDepartmentID,Name,DescriptionFROMCategoryWHERECategoryID=@CategoryID

CatalogGetProductDetails该存储过程用于显示商品明细页。需要显示的信息包括名称、描述、单价和第二张产品图片。CREATEPROCEDURECatalogGetProductDetails(@ProductIDINT)ASSELECTName,Description,Price,Thumbnail,Image,PromoFront,PromoDeptFROMProductWHEREProductID=@ProductID

CatalogGetCategoriesInDepartment当访问者选择一个特定的门类是,除了显示门类详细信息之外,还想显示该门类下的分类。这将由该存储过程完成,它会返回一个门类下的分类列表。CatalogGetCategoriesInDepartment返回属于输入参数@DepartmentID指定的类型的分类ID、名称和描述列表:CREATEPROCEDURECatalogGetCategoriesInDepartment(@DepartmentIDINT)ASSELECTCategoryID,Name,DescriptionFROMCategoryWHEREDepartmentID=@DepartmentID

CatalogGetProductsOnFrontPromoCatalogGetProductsOnFrontPromo返回在目录中的一页特色商品(bit型字段PromoFront的值设置为1)。这个存储过程使用了在本章前面提及的很多理论:存储过程把商品总数保存在@HowManyProducts变量中用一个TABLE变量保存完整的商品列表用ROW_NUMBER函数实现分页CREATEPROCEDURECatalogGetProductsOnFrontPromo(@DescriptionLengthINT,@PageNumberINT,@ProductsPerPageINT,@HowManyProductsINTOUTPUT)AS--declareanewTABLEvariableDECLARE@ProductsTABLE(RowNumberINT,ProductIDINT,NameNVARCHAR(50),DescriptionNVARCHAR(MAX),PriceMONEY,ThumbnailNVARCHAR(50),ImageNVARCHAR(50),PromoFrontbit,PromoDeptbit)--populatethetablevariablewiththecompletelistofproductsINSERTINTO@ProductsSELECTROW_NUMBER()OVER(ORDERBYProduct.ProductID),ProductID,Name,CASEWHENLEN(Description)<=@DescriptionLengthTHENDescriptionELSESUBSTRING(Description,1,@DescriptionLength)+'...'ENDASDescription,Price,Thumbnail,Image,PromoFront,PromoDeptFROMProductWHEREPromoFront=1--returnthetotalnumberofproductsusinganOUTPUTvariableSELECT@HowManyProducts=COUNT(ProductID)FROM@Products--extracttherequestedpageofproductsSELECTProductID,Name,Description,Price,Thumbnail,Image,PromoFront,PromoDeptFROM@ProductsWHERERowNumber>(@PageNumber-1)*@ProductsPerPageANDRowNumber<=@PageNumber*@ProductsPerPage

CatalogGetProductsInCategory当访问者在某门类下选择一个特定的分类是,希望列出该门类下的所有商品列表。实现该功能将使用CatalogGetProductsInCategory存储过程,这个存储过程的大部分内容跟CatalogGetProductsOnFrontPromo存储过程一样,除了实际查询更复杂一些之外:CREATEPROCEDURECatalogGetProductsInCategory(@CategoryIDINT,@DescriptionLengthINT,@PageNumberINT,@ProductsPerPageINT,@HowManyProductsINTOUTPUT)AS--declareanewTABLEvariableDECLARE@ProductsTABLE(RowNumberINT,ProductIDINT,NameNVARCHAR(50),DescriptionNVARCHAR(MAX),PriceMONEY,ThumbnailNVARCHAR(50),ImageNVARCHAR(50),PromoFrontbit,PromoDeptbit)--populatethetablevariablewiththecompletelistofproductsINSERTINTO@ProductsSELECTROW_NUMBER()OVER(ORDERBYProduct.ProductID),Product.ProductID,Name,CASEWHENLEN(Description)<=@DescriptionLengthTHENDescriptionELSESUBSTRING(Description,1,@DescriptionLength)+'...'ENDASDescription,Price,Thumbnail,Image,PromoFront,PromoDeptFROMProductINNERJOINProductCategoryONProduct.ProductID=ProductCategory.ProductIDWHEREProductCategory.CategoryID=@CategoryID--returnthetotalnumberofproductsusinganOUTPUTvariableSELECT@HowManyProducts=COUNT(ProductID)FROM@Products--extracttherequestedpageofproductsSELECTProductID,Name,Description,Price,Thumbnail,Image,PromoFront,PromoDeptFROM@ProductsWHERERowNumber>(@PageNumber-1)*@ProductsPerPageANDRowNumber<=@PageNumber*@ProductsPerPage

CatalogGetProductsOnDeptPromo当访问者选择一个特定的门类时,除了需要列出其名称、描述和其所属的分类列表外,还需要显示该门类下的特色商品列表。CatalogGetProductsOnDeptPromo将返回某门类下的所有PromoDept字段值为1的商品。在CatalogGetProductsOnDeptPromo中,需要哟你个一个表连接来查询属于某分类的商品。现在,只是需要改为查询某门类。CREATEPROCEDURECatalogGetProductsOnDeptPromo(@DepartmentIDINT,@DescriptionLengthINT,@PageNumberINT,@ProductsPerPageINT,@HowManyProductsINTOUTPUT)AS--declareanewTABLEvariableDECLARE@ProductsTABLE(RowNumberINT,ProductIDINT,NameNVARCHAR(50),DescriptionNVARCHAR(MAX),PriceMONEY,ThumbnailNVARCHAR(50),ImageNVARCHAR(50),PromoFrontbit,PromoDeptbit)--populatethetablevariablewiththecompletelistofproductsINSERTINTO@ProductsSELECTROW_NUMBER()OVER(ORDERBYProductID)ASRow,ProductID,Name,SUBSTRING(Description,1,@DescriptionLength)+'...'ASDescription,Price,Thumbnail,Image,PromoFront,PromoDeptFROM(SELECTDISTINCTProduct.ProductID,Product.Name,CASEWHENLEN(Product.Description)<=@DescriptionLengthTHENProduct.DescriptionELSESUBSTRING(Product.Description,1,@DescriptionLength)+'...'ENDASDescription,Price,Thumbnail,Image,PromoFront,PromoDeptFROMProductINNERJOINProductCategoryONProduct.ProductID=ProductCategory.ProductIDINNERJOINCategoryONProductCategory.CategoryID=Category.CategoryIDWHEREProduct.PromoDept=1ANDCategory.DepartmentID=@DepartmentID)ASProductOnDepPr--returnthetotalnumberofproductsusinganOUTPUTvariableSELECT@HowManyProducts=COUNT(ProductID)FROM@Products--extracttherequestedpageofproductsSELECTProductID,Name,Description,Price,Thumbnail,Image,PromoFront,PromoDeptFROM@ProductsWHERERowNumber>(@PageNumber-1)*@ProductsPerPageANDRowNumber<=@PageNumber*@ProductsPerPage六、添加新配置信息(1)打开web.config文件,将以下代码添加到<appSettings>节点中:<appSettings><addkey="MailServer"value="mailserveraddress"/><addkey="MailUsername"value="mailusername"/><addkey="MailPassword"value="mailpassword"/><addkey="MailFrom"value="mailaddress"/><addkey="EnableErrorLogEmail"value="true"/><addkey="ErrorLogEmail"value="errors@"/><addkey="ProductsPerPage"value="6"/><addkey="ProductDescriptionLength"value="60"/><addkey="SiteName"value="BookShop"/></appSettings>(2)打开BookShopConfiguration类,并添加两个字段属性,它们的值在类的静态构造函数中只被赋值一次。publicstaticclassBookShopConfiguration{//CachestheconnectionstringprivatestaticstringdbConnectionString;//CachesthedataprovidernameprivatestaticstringdbProviderName;//StorethenumberofproductsperpageprivatereadonlystaticintproductsPerPage;//StoretheproductdescriptionlengthforproductlistsprivatereadonlystaticintproductDescriptionLength;//StorethenameofyourshopprivatereadonlystaticstringsiteName;//InitializevariouspropertiesintheconstructorstaticBookShopConfiguration(){dbConnectionString=ConfigurationManager.ConnectionStrings["BookShopConnection"].ConnectionString;dbProviderName=ConfigurationManager.ConnectionStrings["BookShopConnection"].ProviderName;productsPerPage=System.Int32.Parse(ConfigurationManager.AppSettings["ProductsPerPage"]);productDescriptionLength=System.Int32.Parse(ConfigurationManager.AppSettings["ProductDescriptionLength"]);siteName=ConfigurationManager.AppSettings["SiteName"];}(3)同时在BookShopConfiguration类中,添加相应的属性以返回在前一步中所添加的字段值。//ReturnsthemaximumnumberofproductstobedisplayedonapagepublicstaticintProductsPerPage{get{returnproductsPerPage;}}//ReturnsthelengthofproductdescriptionsinproductslistspublicstaticintProductDescriptionLength{get{returnproductDescriptionLength;}}//ReturnsthelengthofproductdescriptionsinproductslistspublicstaticstringSiteName{get{returnsiteName;}}

七、在VisualStudio中,打开前面章节所创建的CatalogAccess.cs文件,并准备为它们添加上业务逻辑。

GetDepartmentDetailsGetDepartmentDetails在点击一个门类以显示它的名称和描述时将会被调用。表示层传入所选门类的ID,则返回所选类型的名称和描述。业务层中的GetDepartmentDetails方法,将使用GenericDataAccess.CreateCommand方法获取一个DbCommand对象,然后执行CatalogGetDepartmentDetails存储过程。业务层把返回的数据包装成一个单独的对象,然后把这个对象返回表示层。应该是个什么对象呢?为存储要传递的数据创建一个单独的类(或者结构,本例中使用结构),这个结构的名称为DepartmentDetails,如下所示:publicstructDepartmentDetails{publicstringName;publicstringDescription;}把门类的名称和描述封装成一个DepartmentDetails对象,然后传回给表示层。DepartmentDetails类可以添加到App_Code文件夹中的一个单独文件或是一个已存在的文件中。多数情况下,会为每一个类单独创建一个文件,因为在本例中DepartmentDetails更像CatalogAccess类的一个工具,所以选择把它添加到CatalogAccess.cs文件中。将DepartmentDetails类添加到CatalogAccess.cs的前面(而不是添加到CatalogAccess类里面),如下所示:usingSystem;usingSystem.Data;usingSystem.Data.Common;///<summary>///Wrapsdepartmentdetailsdata///</summary>publicstructDepartmentDetails{publicstringName;publicstringDescription;}///<summary>///Productcatalogbusinesstiercomponent///</summary>publicstaticclassCatalogAccess现在,将GetDepartmentDetails方法添加到CatalogAccess类中。加在那个位置并不重要,但是为了保持代码的组织性,应将其添加到GetDepartments方法后面://getdepartmentdetailspublicstaticDepartmentDetailsGetDepartmentDetails(stringdepartmentId){//getaconfiguredDbCommandobjectDbCommandcomm=GenericDataAccess.CreateCommand();//setthestoredprocedurenamecomm.CommandText="CatalogGetDepartmentDetails";//createanewparameterDbParameterparam=comm.CreateParameter();param.ParameterName="@DepartmentID";param.Value=departmentId;param.DbType=DbType.Int32;comm.Parameters.Add(param);//executethestoredprocedureDataTabletable=GenericDataAccess.ExecuteSelectCommand(comm);//wrapretrieveddataintoaDepartmentDetailsobjectDepartmentDetailsdetails=newDepartmentDetails();if(table.Rows.Count>0){details.Name=table.Rows[0]["Name"].ToString();details.Description=table.Rows[0]["Description"].ToString();}//returndepartmentdetailsreturndetails;}现在,我们应该知道在这个函数中将会发生什么,因为我们在前面章节中已经做了分析。其主要目的是传回相关门类的名称和描述。为此它调用了CatalogGetDepartmentDetails存储过程,并提供了门类ID作为参数。在执行后,该函数读取了@DepartmentName和@DepartmentDescription输出参数,把他们保存在一个DepartmentDetails对象中,然后把这个对象传给调用函数。

GetCategoryDetails在本节中,就像取回所选类型的名称和描述一样,现在需要对分类做相同的是。这里使用同样的技术,把数据封装在一个单独的类中。把CategoryDetails结构添加到CatalogAccess.cs文件的前面。不要把它放在CatalogAccess类中。///<summary>///Wrapscategorydetailsdata///</summary>publicstructCategoryDetails{publicintDepartmentId;publicstringName;publicstringDescription;}然后,将GetCategoryDetails方法添加到CatalogAccess类中。除了它将调用另一个存储过程、使用另一个类来封装返回的信息之外,其他的与GetDepartmentDetails完全相同://GetcategorydetailspublicstaticCategoryDetailsGetCategoryDetails(stringcategoryId){//getaconfiguredDbCommandobjectDbCommandcomm=GenericDataAccess.CreateCommand();//setthestoredprocedurenamecomm.CommandText="CatalogGetCategoryDetails";//createanewparameterDbParameterparam=comm.CreateParameter();param.ParameterName="@CategoryID";param.Value=categoryId;param.DbType=DbType.Int32;comm.Parameters.Add(param);//executethestoredprocedureDataTabletable=GenericDataAccess.ExecuteSelectCommand(comm);//wrapretrieveddataintoaCategoryDetailsobjectCategoryDetailsdetails=newCategoryDetails();if(table.Rows.Count>0){details.DepartmentId=Int32.Parse(table.Rows[0]["DepartmentID"].ToString());details.Name=table.Rows[0]["Name"].ToString();details.Description=table.Rows[0]["Description"].ToString();}//returndepartmentdetailsreturndetails;}

GetProductDetails现在我们将对产品明细也进行同样的操作。在CatalogAccess.cs开始处添加ProductDetails类结构,不要把它房子啊CatalogAccess类中。///<summary>///Wrapsproductdetailsdata///</summary>publicstructProductDetails{publicintProductID;publicstringName;publicstringDescription;publicdecimalPrice;publicstringThumbnail;publicstringImage;publicboolPromoFront;publicboolPromoDept;}将GetCategoryDetails方法添加到CatalogAccess类中://GetproductdetailspublicstaticProductDetailsGetProductDetails(stringproductId){//getaconfiguredDbCommandobjectDbCommandcomm=GenericDataAccess.CreateCommand();//setthestoredprocedurenamecomm.CommandText="CatalogGetProductDetails";//createanewparameterDbParameterparam=comm.CreateParameter();param.ParameterName="@ProductID";param.Value=productId;param.DbType=DbType.Int32;comm.Parameters.Add(param);//executethestoredprocedureDataTabletable=GenericDataAccess.ExecuteSelectCommand(comm);//wrapretrieveddataintoaProductDetailsobjectProductDetailsdetails=newProductDetails();if(table.Rows.Count>0){//getthefirsttablerowDataRowdr=table.Rows[0];//getproductdetailsdetails.ProductID=int.Parse(productId);details.Name=dr["Name"].ToString();details.Description=dr["Description"].ToString();details.Price=Decimal.Parse(dr["Price"].ToString());details.Thumbnail=dr["Thumbnail"].ToString();details.Image=dr["Image"].ToString();details.PromoFront=bool.Parse(dr["PromoFront"].ToString());details.PromoDept=bool.Parse(dr["PromoDept"].ToString());}//returndepartmentdetailsreturndetails;}

GetCategoriesInDepartment调用GetCategoriesInDepartment方法是为了获取某一门类下的分类列表。将该函数添加到CatalogAccess类中://retrievethelistofcategoriesinadepartmentpublicstaticDataTableGetCategoriesInDepartment(stringdepartmentId){//getaconfiguredDbCommandobjectDbCommandcomm=GenericDataAccess.CreateCommand();//setthestoredprocedurenamecomm.CommandText="CatalogGetCategoriesInDepartment";//createanewparameterDbParameterparam=comm.CreateParameter();param.ParameterName="@DepartmentID";param.Value=departmentId;param.DbType=DbType.Int32;comm.Parameters.Add(param);//executethestoredprocedurereturnGenericDataAccess.ExecuteSelectCommand(comm);}

GetProductsOnFrontPromo返回商品信息的方法(如GetProductsOnFrontPromo,GetProductsOnDeptPromo,GetProductsInCategory)要相对复杂些,因为他们需要处理分页。这就意味着需要为命令对象添加三个参数:@PageNumber,@ProductsPerPage,和@HowManyProducts。随后是一个输出参数,它将会被存储过程赋值为符合条件的商品总数(所以就可以计算商品的总页数,并告诉访问者)。另一个新的参数是@DescriptionLength,它指出商品描述将截取多少个字符(我们不会在商品列表中显示完整的商品描述)。GetProductsOnFrontPromo方法用来获取显示在网站主页面的特色商品列表。它有两个参数:pageNumber(页码)和howManyPages(总页数)。最后一个参数howManyPages是一个输出参数。CatalogGetProductsOnFrontPromo存储过程所需要的另两个参数((@DescriptionLength和@ProductsPerPage)的值,要从在先前添加的类字段productsPerPage和productDescriptionLength中获取。当表示层调用GetProductsOnFrontPromo时,以DataTable的形式传回所请求的商品列表,商品的子夜数由howManyPages输出参数传回。将这个方法添加到CatalogAccess类中://RetrievethelistofproductsoncatalogpromotionpublicstaticDataTableGetProductsOnFrontPromo(stringpageNumber,outinthowManyPages){//getaconfiguredDbCommandobjectDbCommandcomm=GenericDataAccess.CreateCommand();//setthestoredprocedurenamecomm.CommandText="CatalogGetProductsOnFrontPromo";//createanewparameterDbParameterparam=comm.CreateParameter();param.ParameterName="@DescriptionLength";param.Value=BookShopConfiguration.ProductDescriptionLength;param.DbType=DbType.Int32;comm.Parameters.Add(param);//createanewparameterparam=comm.CreateParameter();param.ParameterName="@PageNumber";param.Value=pageNumber;param.DbType=DbType.Int32;comm.Parameters.Add(param);//createanewparameterparam=comm.CreateParameter();param.ParameterName="@ProductsPerPage";param.Value=BookShopConfiguration.ProductsPerPage;param.DbType=DbType.Int32;comm.Parameters.Add(param);//createanewparameterparam=comm.CreateParameter();param.ParameterName="@HowManyProducts";param.Direction=ParameterDirection.Output;param.DbType=DbType.Int32;comm.Parameters.Add(param);//executethestoredprocedureandsavetheresultsinaDataTableDataTabletable=GenericDataAccess.ExecuteSelectCommand(comm);//calculatehowmanypagesofproductsandsettheoutparameterinthowManyProducts=Int32.Parse(comm.Parameters["@HowManyProducts"].Value.ToString());howManyPages=(int)Math.Ceiling((double)howManyProducts/(double)BookShopConfiguration.ProductsPerPage);//returnthepageofproductsreturntable;}

GetProductsOnDeptPromoGetProductsOnDeptPromo函数返回一个属于指定门类的特色商品列表。在顾客访问某门类的主页时,就显示该门类的特色商品。//retrievethelistofproductsfeaturedforadepartmentpublicstaticDataTableGetProductsOnDeptPromo(stringdepartmentId,stringpageNumber,outinthowManyPages){//getaconfiguredDbCommandobjectDbCommandcomm=GenericDataAccess.CreateCommand();//setthestoredprocedurenamecomm.CommandText="CatalogGetProductsOnDeptPromo";//createanewparameterDbParameterparam=comm.CreateParameter();param.ParameterName="@DepartmentID";param.Value=departmentId;param.DbType=DbType.Int32;comm.Parameters.Add(param);//createanewparameterparam=comm.CreateParameter();param.ParameterName="@DescriptionLength";param.Value=BookShopConfiguration.ProductDescriptionLength;param.DbType=DbType.Int32;comm.Parameters.Add(param);//createanewparameterparam=comm.CreateParameter();param.ParameterName="@PageNumber";param.Value=pageNumber;param.DbType=DbType.Int32;comm.Parameters.Add(param);//createanewparameterparam=comm.CreateParameter();param.ParameterName="@ProductsPerPage";param.Value=BookShopConfiguration.ProductsPerPage;param.DbType=DbType.Int32;comm.Parameters.Add(param);//createanewparameterparam=comm.CreateParameter();param.ParameterName="@HowManyProducts";param.Direction=ParameterDirection.Output;param.DbType=DbType.Int32;comm.Parameters.Add(param);//executethestoredprocedureandsavetheresultsinaDataTableDataTabletable=GenericDataAccess.ExecuteSelectCommand(comm);//calculatehowmanypagesofproductsandsettheoutparameterinthowManyProducts=Int32.Parse(comm.Parameters["@HowManyProducts"].Value.ToString());howManyPages=(int)Math.Ceiling((double)howManyProducts/(double)BookShopConfiguration.ProductsPerPage);//returnthepageofproductsreturntable;}

GetProductsInCategoryGetProductsInCategory函数返回一个属于指定类的商品列表。将下面的方法添加到CatalogAccess类中://retrievethelistofproductsinacategorypublicstaticDataTableGetProductsInCategory(stringcategoryId,stringpageNumber,outinthowManyPages){//getaconfiguredDbCommandobjectDbCommandcomm=GenericDataAccess.CreateCommand();//setthestoredprocedurenamecomm.CommandText="CatalogGetProductsInCategory";//createanewparameterDbParameterparam=comm.CreateParameter();param.ParameterName="@CategoryID";param.Value=categoryId;param.DbType=DbType.Int32;comm.Parameters.Add(param);//createanewparameterparam=comm.CreateParameter();param.ParameterName="@DescriptionLength";param.Value=BalloonShopConfiguration.ProductDescriptionLength;param.DbType=DbType.Int32;comm.Parameters.Add(param);//createanewparameterparam=comm.CreateParameter();param.ParameterName="@PageNumber";param.Value=pageNumber;param.DbType=DbType.Int32;comm.Parameters.Add(param);//createanewparameterparam=comm.CreateParameter();param.ParameterName="@ProductsPerPage";param.Value=BalloonShopConfiguration.ProductsPerPage;param.DbType=DbType.Int32;comm.Parameters.Add(param);//createanewparameterparam=comm.CreateParameter();param.ParameterName="@HowManyProducts";param.Direction=ParameterDirection.Output;param.DbType=DbType.Int32;comm.Parameters.Add(param);//executethestoredprocedureandsavetheresultsinaDataTableDataTabletable=GenericDataAccess.ExecuteSelectCommand(comm);//calculatehowmanypagesofproductsandsettheoutparameterinthowManyProducts=Int32.Parse(comm.Parameters["@HowManyProducts"].Value.ToString());howManyPages=(int)Math.Ceiling((double)howManyProducts/(double)BalloonShopConfiguration.ProductsPerPage);//returnthepageofproductsreturntable;}

完成LinkFactory类添加ToCategory,ToProduct和ToProductImage方法到Link类中:publicstaticstringToCategory(stringdepartmentId,stringcategoryId,stringpage){if(page=="1")returnBuildAbsolute(String.Format("Catalog.aspx?DepartmentID={0}&CategoryID={1}",departmentId,categoryId));elsereturnBuildAbsolute(String.Format("Catalog.aspx?DepartmentID={0}&CategoryID={1}&Page={2}",departmentId,categoryId,page));}publicstaticstringToCategory(stringdepartmentId,stringcategoryId){returnToCategory(departmentId,categoryId,"1");}publicstaticstringToProduct(stringproductId){returnBuildAbsolute(String.Format("Product.aspx?ProductID={0}",productId));}publicstaticstringToProductImage(stringfileName){//buildproductURLreturnBuildAbsolute("/ProductImages/"+fileName);}八、创建Web用户控件CategoriesLIst(1)在UserControls文件夹中新建一个Web用户控件。在解决方案管理器中,右击UserControls文件夹,选择添加新项。选择Web用户控件模板,然后设置其名称为CategoriesList.ascx,确定选中将代码房子单独的文件中选项,然后点击添加。(2)在该用户控件中添加DataList控件,并按下图所示设置DataList对象属性。

屏幕剪辑的捕获时间:2011/9/2523:12(3)切换到设计视图中,右击DataList,然后选择编辑模板-〉页眉和页脚模板-〉HeaderTemplate。在模板的页面模板中输入“选择一个分类”。(4)右击DataList,选择编辑模板->项模板->ItemTemplate。从工具箱中的标准中,选择一个HyperLink控件添加到ItemTmplate中。并把它的Text属性置为空字符串。(5)切换到源视图。将看到有VisualStudio为HyperLink控件自动产生的代码,如下所示:<%@ControlLanguage="C#"AutoEventWireup="true"CodeFile="CategoriesList->ItemTemplateascx.cs"Inherits="UserControls_CategoriesList"%><asp:DataListID="list"runat="server"CssClass="CategoryListContent"Width="200px"><HeaderStyleCssClass="CategoryListHead"/><HeaderTemplate>选择一个分类</HeaderTemplate><ItemTemplate><asp:HyperLinkID="HyperLink1"runat="server">[HyperLink1]</asp:HyperLink></ItemTemplate></asp:DataList>

(6)修改<ItemTemplate>元素的代码,如下所示:<ItemTemplate><asp:HyperLinkID="HyperLink1"Runat="server"NavigateUrl='<%#Link.ToCategory(Request.QueryString["DepartmentID"],Eval("CategoryID").ToString())%>'Text='<%#HttpUtility.HtmlEncode(Eval("Name").ToString())%>'ToolTip='<%#HttpUtility.HtmlEncode(Eval("Description").ToString())%>'CssClass='<%#Eval("CategoryID").ToString()==Request.QueryString["CategoryID"]?"CategorySelected":"CategoryUnselected"%>'>></asp:HyperLink></ItemTemplate>(7)切换到设计视图将会看到如下图所示效果:

(8)将下面的样式添加到BookShop.css文件中:.CategoriesList{border:#ea6d001pxsolid;text-align:center;margin-top:20px;}.CategoriesListHead{border:#ea6d001pxsolid;background-color:#f8c78c;}a.CategoryUnselected{line-height:25px;text-decoration:none;color:Black;}a.CategoryUnselected:hover{text-decoration:underline;}a.CategorySelected{line-height:25px;font-weight:bold;text-decoration:none;color:Black;}(9)打开控件的后台代码文件(CategoriesList.ascx.cs)并修改Page_Load事件处理程序:protectedvoidPage_Load(objectsender,EventArgse){//ObtaintheIDoftheselecteddepartmentstringdepartmentId=Request.QueryString["DepartmentID"];//ContinueonlyifDepartmentIDexistsinthequerystringif(departmentId!=null){//Catalog.GetCategoriesInDepartmentreturnsaDataTable//objectcontainingcategorydata,whichisdisplayedbytheDataListlist.DataSource=CatalogAccess.GetCategoriesInDepartment(departmentId);//Neededtobindthedataboundcontrolstothedatasourcelist.DataBind();}}(10)在设计视图中打开BookShop.master母版页,并从解决方案管理器中将CatagoriesLIst.ascx拖到门类列表附近。(11)执行项目,选择一个门类,案后选择一个分类,你讲看到的效果如下:

九、显示门类和分类数据(1)、在源视图中打开Catalog.aspx。在此需要添加两个Label控件,分别命名为CatalogTitleLabel和CatalogDescriotionLabel,放在页面代码的内容部分。你可以在设计视图中添加它们,也可以在代码视图中添加下面的HTML代码,完成这两个Label控件的添加工作:<%@PageLanguage="C#"MasterPageFile="~/BalloonShop.master"AutoEventWireup="true"CodeFile="Catalog.aspx.cs"Inherits="Catalog"Title="BalloonShop:Catalog"%><asp:ContentID="Content1"ContentPlaceHolderID="head"runat="Server"></asp:Content><asp:ContentID="Content2"ContentPlaceHolderID="ContentPlaceHolder1"runat="server"><h1><asp:LabelID="catalogTitleLabel"CssClass="CatalogTitle"runat="server"/></h1><h2><asp:LabelID="catalogDescriptionLabel"CssClass="CatalogDescription"runat="server"/></h2>[PlaceListofProductsHere]</asp:Content>(2)、在源视图中打开Default.aspx,将内容占位符的代码修改为:<asp:ContentID="Content2"ContentPlaceHolderID="ContentPlaceHolder1"runat="server"><h1><spanclass="CatalogTitle">欢迎访问BookShop!</span></h1><h2><spanclass="CatalogDescription">本周我们将对以下精彩书籍进行特价销售:</span></h2>[PlaceListofProductsHere]</asp:Content>3、将以下样式添加到BalloonShop.css中.CatalogTitle{color:red;font-size:24px;font-weight:bold;}.CatalogDescription{color:Black;font-weight:bold;font-size:14px;}4、现在编写代码,来给这两个Label控件填充从数据库中获取的数据。将下面的代码添加到Catalog.aspx.cs文件的Catalog类中。publicpartialclassCatalog:System.Web.UI.Page{protectedvoidPage_Load(objectsender,EventArgse){PopulateControls();}//FillthepagewithdataprivatevoidPopulateControls(){//RetrieveDepartmentIDfromthequerystringstringdepartmentId=Request.QueryString["DepartmentID"];//RetrieveCategoryIDfromthequerystringstringcategoryId=Request.QueryString["CategoryID"];//Ifbrowsingacategory...if(categoryId!=null){//RetrievecategoryanddepartmentdetailsanddisplaythemCategoryDetailscd=CatalogAccess.GetCategoryDetails(categoryId);catalogTitleLabel.Text=HttpUtility.HtmlEncode(cd.Name);DepartmentDetailsdd=CatalogAccess.GetDepartmentDetails(departmentId);catalogDescriptionLabel.Text=HttpUtility.HtmlEncode(cd.Description);//Setthetitleofthepagethis.Title=HttpUtility.HtmlEncode(BalloonShopConfiguration.SiteName+":"+dd.Name+":"+cd.Name);}//Ifbrowsingadepartment...elseif(departmentId!=null){//RetrievedepartmentdetailsanddisplaythemDepartmentDetailsdd=CatalogAccess.GetDepartmentDetails(departmentId);catalogTitleLabel.Text=HttpUtility.HtmlEncode(dd.Name);catalogDescriptionLabel.Text=HttpUtility.HtmlEncode(dd.Description);//Setthetitleofthepagethis.Title=HttpUtility.HtmlEncode(BalloonShopConfiguration.SiteName+":"+dd.Name);}}}(5)执行该项目,然后点击其中的一个门类,将会得到如下图所示的界面。然后针对分类做同样的测试。

十、创建Web用户控件ProductsList(1)把配套代码中的ProductImages文件夹复制到BookShop解决方案中。(2)在UserControls文件夹中添加一个新的Web用户控件,命名为Pager。(3)在源代码视图中,添加Pager的模板代码。<%@ControlLanguage="C#"AutoEventWireup="true"CodeFile="Pager.ascx.cs"Inherits="UserControlsPager"%><p>Page<asp:LabelID="currentPageLabel"runat="server"/>of<asp:LabelID="howManyPagesLabel"runat="server"/>|<asp:HyperLinkID="previousLink"Runat="server">Previous</asp:HyperLink><asp:RepeaterID="pagesRepeater"runat="server"><ItemTemplate><asp:HyperLinkID="hyperlink"runat="server"Text='<%#Eval("Page")%>'NavigateUrl='<%#Eval("Url")%>'/></ItemTemplate></asp:Repeater><asp:HyperLinkID="nextLink"Runat="server">Next</asp:HyperLink></p>(4)切换到设计视图,你将会看到如下效果(5)

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论