Tải bản đầy đủ (.pdf) (22 trang)

Lập trình ASP.net potx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (173.45 KB, 22 trang )

1

Nguyễn Phạm Phương Nam - Bộ môn CNPM – Khoa CNTT - DHKHTN



11
Môn học:
Phát triển ứng dụng Web nâng cao với ASP.NET
Product Catalog – P2
TRƯỜNG ĐẠI HỌC KHOA HỌC TỰ NHIÊN
KHOA CÔNG NGHỆ THÔNG TIN
BỘ MÔN CÔNG NGHỆ PHẦN MỀM


Phát tri

n

ng d

ng Web ASP.NET


08CDITEC

2010


2


Trần Phượng Hoàng – PTN BMCNPM – Khoa CNTT – DHKHTN

1 Xây dưng thành phần Data Tier
1.1 Tạo các Data Table
1.1.1 Category

USE BalloonShop

GO


CREATE TABLE Category(
CategoryID INT IDENTITY(1,1) NOT NULL,
DepartmentID INT NOT NULL,
Name NVARCHAR(50) NOT NULL,
Description NVARCHAR(1000) NULL,
CONSTRAINT PK_Category_1 PRIMARY KEY CLUSTERED(CategoryID ASC)
)

GO

ALTER TABLE Category ADD CONSTRAINT FK_Category_Department FOREIGN
KEY(DepartmentID)
REFERENCES Department (DepartmentID)

GO


USE BalloonShop
GO


TRUNCATE TABLE Category
GO

SET IDENTITY_INSERT Category ON
GO

INSERT INTO Category (CategoryID, DepartmentID, Name, Description )
VALUES (1, 1, 'Love & Romance', 'Here''s our collection of balloons with
romantic messages.')

INSERT INTO Category (CategoryID, DepartmentID, Name, Description )
VALUES (2, 1, 'Birthdays', 'Tell someone "Happy Birthday" with one of these
wonderful balloons!')

INSERT INTO Category (CategoryID, DepartmentID, Name, Description )
VALUES (3, 1, 'Weddings', 'Going to a wedding? Here''s a collection of
balloons for that special event!')

INSERT INTO Category (CategoryID, DepartmentID, Name, Description )
VALUES (4, 2, 'Message Balloons', 'Why write on paper, when you can deliver
your message on a balloon?')
Phát tri

n

ng d

ng Web ASP.NET



08CDITEC

2010


3

Nguyễn Phạm Phương Nam - Bộ môn CNPM – Khoa CNTT - DHKHTN


INSERT INTO Category (CategoryID, DepartmentID, Name, Description )
VALUES (5, 2, 'Cartoons', 'Buy a balloon with your child''s favorite cartoon
character!')

INSERT INTO Category (CategoryID, DepartmentID, Name, Description )
VALUES (6, 2, 'Miscellaneous', 'Various baloons that your kid will most
certainly love!')

GO

SET IDENTITY_INSERT Category OFF
GO

1.1.2 Product

USE BalloonShop

GO


CREATE TABLE Product(
ProductID INT IDENTITY(1,1) NOT NULL,
Name NVARCHAR(50) NOT NULL,
Description NVARCHAR(MAX) NOT NULL,
Price MONEY NOT NULL,
Image1FileName NVARCHAR(50) NULL,
Image2FileName NVARCHAR(50) NULL,
OnCatalogPromotion BIT NOT NULL,
OnDepartmentPromotion BIT NOT NULL,
CONSTRAINT PK_Product PRIMARY KEY CLUSTERED (ProductID ASC)
)

USE BalloonShop
GO

TRUNCATE TABLE Product
GO

SET IDENTITY_INSERT Product ON
GO

INSERT INTO Product(ProductID, Name, Description, Price, Image1FileName,
Image2FileName, OnCatalogPromotion, OnDepartmentPromotion )
VALUES (1, 'I Love You (Simon Elvin)', 'An adorable romantic balloon by Simon
Elvin. You''ll fall in love with the cute bear bearing a bouquet of roses, a
heart with I Love You, and a card.', 121.9900, 't0326801.jpg', '0326801.jpg',
0, 1)
GO



Phát tri

n

ng d

ng Web ASP.NET


08CDITEC

2010


4

Trần Phượng Hoàng – PTN BMCNPM – Khoa CNTT – DHKHTN

Ghi chú: Sử dụng các file script được cung cấp sẵn để tạo đầy đủ CSDL
1.1.3 ProductCategory

USE BalloonShop

GO

CREATE TABLE ProductCategory(
ProductID INT NOT NULL,
CategoryID INT NOT NULL,
CONSTRAINT PK_ProductCategory PRIMARY KEY CLUSTERED (ProductID ASC,
CategoryID ASC)

)

GO

ALTER TABLE ProductCategory WITH CHECK ADD CONSTRAINT
FK_ProductCategory_Category FOREIGN KEY(CategoryID)
REFERENCES Category (CategoryID)

GO

ALTER TABLE ProductCategory WITH CHECK ADD CONSTRAINT
FK_ProductCategory_Product FOREIGN KEY(ProductID)
REFERENCES Product (ProductID)

USE BalloonShop
GO

INSERT INTO ProductCategory(ProductID, CategoryID)
VALUES(1, 1)
GO


1.2 Thành phần Store Procedure
- Ý nghĩa ?
- Input và Output parameter
USE BalloonShop
GO

CREATE PROCEDURE GetDepartmentDetails
(@DepartmentID INT)

AS
SELECT Name, Description
FROM Department
WHERE DepartmentID = @DepartmentID
Phát tri

n

ng d

ng Web ASP.NET


08CDITEC

2010


5

Nguyễn Phạm Phương Nam - Bộ môn CNPM – Khoa CNTT - DHKHTN


GO

CREATE PROCEDURE GetCategoryDetails
(@CategoryID INT)
AS
SELECT DepartmentID, Name, Description
FROM Category

WHERE CategoryID = @CategoryID

GO

CREATE PROCEDURE GetProductDetails
(@ProductID INT)
AS
SELECT Name, Description, Price, Image1FileName, Image2FileName,
OnCatalogPromotion, OnDepartmentPromotion
FROM Product
WHERE ProductID = @ProductID

GO

CREATE PROCEDURE GetCategoriesInDepartment
(@DepartmentID INT)
AS
SELECT CategoryID, Name, Description
FROM Category
WHERE DepartmentID = @DepartmentID

GO

CREATE PROCEDURE GetProductsOnCatalogPromotion
(@DescriptionLength INT,
@PageNumber INT,
@ProductsPerPage INT,
@HowManyProducts INT OUTPUT)
AS


declare a new TABLE variable
DECLARE @Products TABLE
(RowNumber INT,
ProductID INT,
Name NVARCHAR(50),
Description NVARCHAR(MAX),
Price MONEY,
Image1FileName NVARCHAR(50),
Image2FileName NVARCHAR(50),
OnCatalogPromotion bit,
OnDepartmentPromotion bit)


populate the table variable with the complete list of products
INSERT INTO @Products
SELECT ROW_NUMBER() OVER (ORDER BY Product.ProductID),
ProductID, Name,
Phát tri

n

ng d

ng Web ASP.NET


08CDITEC

2010



6

Trần Phượng Hoàng – PTN BMCNPM – Khoa CNTT – DHKHTN

CASE WHEN LEN(Description) <= @DescriptionLength THEN Description
ELSE SUBSTRING(Description, 1, @DescriptionLength) + ' ' END
AS Description, Price, Image1FileName, Image2FileName,
OnCatalogPromotion, OnDepartmentPromotion
FROM Product
WHERE OnCatalogPromotion = 1

return the total number of products using an OUTPUT variable
SELECT @HowManyProducts = COUNT(ProductID) FROM @Products

extract the requested page of products
SELECT ProductID, Name, Description, Price, Image1FileName,
Image2FileName, OnCatalogPromotion, OnDepartmentPromotion
FROM @Products
WHERE RowNumber > (@PageNumber - 1) * @ProductsPerPage
AND RowNumber <= @PageNumber * @ProductsPerPage

GO

CREATE PROCEDURE GetProductsInCategory
(@CategoryID INT,
@DescriptionLength INT,
@PageNumber INT,
@ProductsPerPage INT,
@HowManyProducts INT OUTPUT)

AS

declare a new TABLE variable
DECLARE @Products TABLE
(RowNumber INT,
ProductID INT,
Name NVARCHAR(50),
Description NVARCHAR(MAX),
Price MONEY,
Image1FileName NVARCHAR(50),
Image2FileName NVARCHAR(50),
OnCatalogPromotion bit,
OnDepartmentPromotion bit)


populate the table variable with the complete list of products
INSERT INTO @Products
SELECT ROW_NUMBER() OVER (ORDER BY Product.ProductID),
Product.ProductID, Name,
CASE WHEN LEN(Description) <= @DescriptionLength THEN Description
ELSE SUBSTRING(Description, 1, @DescriptionLength) + ' ' END
AS Description, Price, Image1FileName, Image2FileName,
OnCatalogPromotion, OnDepartmentPromotion
FROM Product INNER JOIN ProductCategory
ON Product.ProductID = ProductCategory.ProductID
WHERE ProductCategory.CategoryID = @CategoryID

return the total number of products using an OUTPUT variable
SELECT @HowManyProducts = COUNT(ProductID) FROM @Products


extract the requested page of products
Phát tri

n

ng d

ng Web ASP.NET


08CDITEC

2010


7

Nguyễn Phạm Phương Nam - Bộ môn CNPM – Khoa CNTT - DHKHTN

SELECT ProductID, Name, Description, Price, Image1FileName,
Image2FileName, OnCatalogPromotion, OnDepartmentPromotion
FROM @Products
WHERE RowNumber > (@PageNumber - 1) * @ProductsPerPage
AND RowNumber <= @PageNumber * @ProductsPerPage


GO

CREATE PROCEDURE GetProductsOnDepartmentPromotion
(@DepartmentID INT,

@DescriptionLength INT,
@PageNumber INT,
@ProductsPerPage INT,
@HowManyProducts INT OUTPUT)
AS

declare a new TABLE variable
DECLARE @Products TABLE
(RowNumber INT,
ProductID INT,
Name NVARCHAR(50),
Description NVARCHAR(MAX),
Price MONEY,
Image1FileName NVARCHAR(50),
Image2FileName NVARCHAR(50),
OnCatalogPromotion bit,
OnDepartmentPromotion bit)

populate the table variable with the complete list of products
INSERT INTO @Products
SELECT ROW_NUMBER() OVER (ORDER BY ProductID) AS Row,
ProductID, Name, SUBSTRING(Description, 1, @DescriptionLength)
+ ' ' AS Description,
Price, Image1FileName, Image2FileName, OnCatalogPromotion,
OnDepartmentPromotion
FROM
(SELECT DISTINCT Product.ProductID, Product.Name,
CASE WHEN LEN(Product.Description) <= @DescriptionLength
THEN Product.Description
ELSE SUBSTRING(Product.Description, 1, @DescriptionLength) +

' ' END
AS Description, Price, Image1FileName, Image2FileName,
OnCatalogPromotion, OnDepartmentPromotion
FROM Product INNER JOIN ProductCategory
ON Product.ProductID = ProductCategory.ProductID
INNER JOIN Category
ON ProductCategory.CategoryID = Category.CategoryID
WHERE Product.OnDepartmentPromotion = 1
AND Category.DepartmentID = @DepartmentID
) AS ProductOnDepPr

return the total number of products using an OUTPUT variable
SELECT @HowManyProducts = COUNT(ProductID) FROM @Products

Phát tri

n

ng d

ng Web ASP.NET


08CDITEC

2010


8


Trần Phượng Hoàng – PTN BMCNPM – Khoa CNTT – DHKHTN

extract the requested page of products
SELECT ProductID, Name, Description, Price, Image1FileName,
Image2FileName, OnCatalogPromotion, OnDepartmentPromotion
FROM @Products
WHERE RowNumber > (@PageNumber - 1) * @ProductsPerPage
AND RowNumber <= @PageNumber * @ProductsPerPage

GO

2 Xây dựng thành phần Business Tier
2.1 Web.config
- Thêm vào các thành phần trong web.config
<appSettings>
……………
<add key="ProductsPerPage" value="6"/>
<add key="ProductDescriptionLength" value="60"/>
<add key="SiteName" value="BalloonShop"/>

</appSettings>
2.2 BalloonShopConfiguration class
- Thêm và thay đổi một số thành phần
private readonly static int productsPerPage;

public static int ProductsPerPage
{
get { return BalloonShopConfiguration.productsPerPage; }
}


private readonly static int productDescriptionLength;

public static int ProductDescriptionLength
{
get { return BalloonShopConfiguration.productDescriptionLength; }
}

private readonly static string siteName;

public static string SiteName
{
get { return BalloonShopConfiguration.siteName; }
}


Phát tri

n

ng d

ng Web ASP.NET


08CDITEC

2010


9


Nguyễn Phạm Phương Nam - Bộ môn CNPM – Khoa CNTT - DHKHTN

static BalloonShopConfiguration()
{
dbConnectionString =
ConfigurationManager.ConnectionStrings["BalloonShopConnection"].ConnectionStr
ing;
dbProviderName =
ConfigurationManager.ConnectionStrings["BalloonShopConnection"].ProviderName;
productsPerPage =
Int32.Parse(ConfigurationManager.AppSettings["ProductsPerPage"].ToString());
productDescriptionLength =
Int32.Parse(ConfigurationManager.AppSettings["ProductDescriptionLength"].ToSt
ring());

}



2.3 CatalogAccess class
- Thêm và thay đổi một số thành phần
2.3.1 DepartmentDetails
-
Thêm thành phần
struct DepartmentDetails

using System;
using System.Data;
using System.Data.Common;


/// <summary>
/// Summary description for CatalogAccess
/// </summary>
///
public struct DepartmentDetails
{
public string Name;
public string Description;
}

public static class CatalogAccess
{
static CatalogAccess()
{

}
}



Phát tri

n

ng d

ng Web ASP.NET



08CDITEC

2010


10

Trần Phượng Hoàng – PTN BMCNPM – Khoa CNTT – DHKHTN

- Thêm method (hàm)
GetDepartmentDetails

public static DepartmentDetails GetDepartmentDetails(string departmentId)
{
// get a configured DbCommand object
DbCommand comm = GenericDataAccess.CreateCommand();
// set the stored procedure name
comm.CommandText = "GetDepartmentDetails";
// create a new parameter
DbParameter param = comm.CreateParameter();
param.ParameterName = "@DepartmentID";
param.Value = departmentId;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// execute the stored procedure
DataTable table = GenericDataAccess.ExecuteSelectCommand(comm);
// wrap retrieved data into a DepartmentDetails object
DepartmentDetails details = new DepartmentDetails();
if (table.Rows.Count > 0)
{


details.Name = table.Rows[0]["Name"].ToString();
details.Description = table.Rows[0]["Description"].ToString();
}
// return department details
return details;
}


2.3.2 CategoryDetails
-
Thêm thành phần
struct CategoryDetails

public struct CategoryDetails
{
public int DepartmentId;
public string Name;
public string Description;
}

- Thêm method (hàm)
GetCategoryDetails

public static CategoryDetails GetCategoryDetails(string categoryId)
{
// get a configured DbCommand object
DbCommand comm = GenericDataAccess.CreateCommand();
// set the stored procedure name
comm.CommandText = "GetCategoryDetails";

// create a new parameter
DbParameter param = comm.CreateParameter();
param.ParameterName = "@CategoryID";
param.Value = categoryId;
param.DbType = DbType.Int32;
Phát tri

n

ng d

ng Web ASP.NET


08CDITEC

2010


11

Nguyễn Phạm Phương Nam - Bộ môn CNPM – Khoa CNTT - DHKHTN

comm.Parameters.Add(param);

// execute the stored procedure
DataTable table = GenericDataAccess.ExecuteSelectCommand(comm);
// wrap retrieved data into a CategoryDetails object
CategoryDetails details = new CategoryDetails();
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();
}
// return department details
return details;
}

2.3.3 ProductDetails
-
Thêm thành phần
struct ProductDetails

public struct ProductDetails
{
public string Name;
public string Description;
public decimal Price;
public string Image1FileName;
public string Image2FileName;
public bool OnDepartmentPromotion;
public bool OnCatalogPromotion;
}

- Thêm method (hàm)
GetProductDetails



public static ProductDetails GetProductDetails(string productId)
{
// get a configured DbCommand object
DbCommand comm = GenericDataAccess.CreateCommand();
// set the stored procedure name
comm.CommandText = "GetProductDetails";
// create a new parameter
DbParameter param = comm.CreateParameter();
param.ParameterName = "@ProductID";
param.Value = productId;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// execute the stored procedure
DataTable table = GenericDataAccess.ExecuteSelectCommand(comm);
// wrap retrieved data into a ProductDetails object
ProductDetails details = new ProductDetails();
if (table.Rows.Count > 0)
{
// get the first table row
Phát tri

n

ng d

ng Web ASP.NET


08CDITEC


2010


12

Trần Phượng Hoàng – PTN BMCNPM – Khoa CNTT – DHKHTN

DataRow dr = table.Rows[0];
// get product details
details.Name = dr["Name"].ToString();
details.Description = dr["Description"].ToString();
details.Price = Decimal.Parse(dr["Price"].ToString());
details.Image1FileName = dr["Image1FileName"].ToString();
details.Image2FileName = dr["Image2FileName"].ToString();
details.OnDepartmentPromotion =
bool.Parse(dr["OnDepartmentPromotion"].ToString());
details.OnCatalogPromotion =
bool.Parse(dr["OnCatalogPromotion"].ToString());
}
// return department details
return details;
}

2.3.4 Mở rộng
- Thêm method (hàm)
GetCategoryinDepartment

public static DataTable GetCategoriesInDepartment(string departmentId)
{
// get a configured DbCommand object

DbCommand comm = GenericDataAccess.CreateCommand();
// set the stored procedure name
comm.CommandText = "GetCategoriesInDepartment";
// create a new parameter
DbParameter param = comm.CreateParameter();
param.ParameterName = "@DepartmentID";
param.Value = departmentId;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// execute the stored procedure
return GenericDataAccess.ExecuteSelectCommand(comm);
}

- Thêm method (hàm)
GetProductsOnCatalogPromotion

public static DataTable GetProductsOnCatalogPromotion(string pageNumber,
out int howManyPages)
{
// get a configured DbCommand object
DbCommand comm = GenericDataAccess.CreateCommand();
// set the stored procedure name
comm.CommandText = "GetProductsOnCatalogPromotion";
// create a new parameter
DbParameter param = comm.CreateParameter();
param.ParameterName = "@DescriptionLength";
param.Value = BalloonShopConfiguration.ProductDescriptionLength;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// create a new parameter

param = comm.CreateParameter();
param.ParameterName = "@PageNumber";
param.Value = pageNumber;
Phát tri

n

ng d

ng Web ASP.NET


08CDITEC

2010


13

Nguyễn Phạm Phương Nam - Bộ môn CNPM – Khoa CNTT - DHKHTN

param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// create a new parameter
param = comm.CreateParameter();
param.ParameterName = "@ProductsPerPage";
param.Value = BalloonShopConfiguration.ProductsPerPage;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// create a new parameter

param = comm.CreateParameter();
param.ParameterName = "@HowManyProducts";
param.Direction = ParameterDirection.Output;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// execute the stored procedure and save the results in a DataTable
DataTable table = GenericDataAccess.ExecuteSelectCommand(comm);
// calculate how many pages of products and set the out parameter
int howManyProducts = Int32.Parse(comm.Parameters
["@HowManyProducts"].Value.ToString());
howManyPages = (int)Math.Ceiling((double)howManyProducts /
(double)BalloonShopConfiguration.ProductsPerPage);
// return the page of products
return table;
}

- Thêm method (hàm)
GetProductsOnCatalogPromotion

public static DataTable GetProductsOnDepartmentPromotion
(string departmentId, string pageNumber, out int howManyPages)
{
// get a configured DbCommand object
DbCommand comm = GenericDataAccess.CreateCommand();
// set the stored procedure name
comm.CommandText = "GetProductsOnDepartmentPromotion";
// create a new parameter
DbParameter param = comm.CreateParameter();
param.ParameterName = "@DepartmentID";
param.Value = departmentId;

param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// create a new parameter
param = comm.CreateParameter();
param.ParameterName = "@DescriptionLength";
param.Value = BalloonShopConfiguration.ProductDescriptionLength;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// create a new parameter
param = comm.CreateParameter();
param.ParameterName = "@PageNumber";
param.Value = pageNumber;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// create a new parameter
param = comm.CreateParameter();
Phát tri

n

ng d

ng Web ASP.NET


08CDITEC

2010



14

Trần Phượng Hoàng – PTN BMCNPM – Khoa CNTT – DHKHTN

param.ParameterName = "@ProductsPerPage";
param.Value = BalloonShopConfiguration.ProductsPerPage;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// create a new parameter
param = comm.CreateParameter();
param.ParameterName = "@HowManyProducts";
param.Direction = ParameterDirection.Output;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// execute the stored procedure and save the results in a DataTable
DataTable table = GenericDataAccess.ExecuteSelectCommand(comm);
// calculate how many pages of products and set the out parameter
int howManyProducts = Int32.Parse
(comm.Parameters["@HowManyProducts"].Value.ToString());
howManyPages = (int)Math.Ceiling((double)howManyProducts /
(double)BalloonShopConfiguration.ProductsPerPage);
// return the page of products
return table;
}


- Thêm method (hàm)
GetProductsInCategory

public static DataTable GetProductsInCategory

(string categoryId, string pageNumber, out int howManyPages)
{
// get a configured DbCommand object
DbCommand comm = GenericDataAccess.CreateCommand();
// set the stored procedure name
comm.CommandText = "GetProductsInCategory";
// create a new parameter
DbParameter param = comm.CreateParameter();
param.ParameterName = "@CategoryID";
param.Value = categoryId;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// create a new parameter
param = comm.CreateParameter();
param.ParameterName = "@DescriptionLength";
param.Value = BalloonShopConfiguration.ProductDescriptionLength;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// create a new parameter
param = comm.CreateParameter();
param.ParameterName = "@PageNumber";
param.Value = pageNumber;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// create a new parameter
param = comm.CreateParameter();
param.ParameterName = "@ProductsPerPage";
param.Value = BalloonShopConfiguration.ProductsPerPage;
param.DbType = DbType.Int32;
Phát tri


n

ng d

ng Web ASP.NET


08CDITEC

2010


15

Nguyễn Phạm Phương Nam - Bộ môn CNPM – Khoa CNTT - DHKHTN

comm.Parameters.Add(param);
// create a new parameter
param = comm.CreateParameter();
param.ParameterName = "@HowManyProducts";
param.Direction = ParameterDirection.Output;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
// execute the stored procedure and save the results in a DataTable
DataTable table = GenericDataAccess.ExecuteSelectCommand(comm);
// calculate how many pages of products and set the out parameter
int howManyProducts = Int32.Parse
(comm.Parameters["@HowManyProducts"].Value.ToString());
howManyPages = (int)Math.Ceiling((double)howManyProducts /

(double)BalloonShopConfiguration.ProductsPerPage);
// return the page of products
return table;
}

3 Xây dựng thành phần Presentation Tier
3.1 List of Categories
- Tạo User Control CategoriesList.ascx
- Thành phần GUI
<div style="clear: both; background-color: #67a3fb; width:195px;">
<asp:DataList ID="list" runat="server">
<ItemTemplate>
<div style="padding-left: 20px; clear: both; height: 25px;
width:100%">
<asp:HyperLink ID="Hyperlink1" runat="server"
NavigateUrl='<%# " /Catalog.aspx?DepartmentID=" +
Request.QueryString["DepartmentID"] + "&CategoryID=" + Eval("CategoryID")%>'
Text=' <%# "&diams; " + Eval("Name") %>'
ToolTip='<%# Eval("Description") %>'
CssClass="footermenu">
</asp:HyperLink>
</div>
</ItemTemplate>
</asp:DataList>
</div>

- Thành phần code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)

{
string departmentId = Request.QueryString["DepartmentID"];

Phát tri

n

ng d

ng Web ASP.NET


08CDITEC

2010


16

Trần Phượng Hoàng – PTN BMCNPM – Khoa CNTT – DHKHTN

if (departmentId != null)
{

DataTable dt = CatalogAccess.GetCategoriesInDepartment(departmentId);
string categoryID = Request.QueryString["CategoryID"];
if (!string.IsNullOrEmpty(categoryID))
{
for (int i = 0; i < dt.Rows.Count; i++)
{

if (dt.Rows[i]["CategoryID"].ToString() == categoryID)
{
dt.Rows[i]["Name"] = "<b>" + dt.Rows[i]["Name"] + "</b>";
}
}
}
list.DataSource = dt;

list.DataBind();

}
else
{
this.Visible = false;
}
}
}


- Thêm thành phần CategoriesList.ascx vào thành phần DepartmentsList.ascx (thực
hiện theo hướng dẫn)
o Kéo thả
o Xử lý hàm sự kiện ItemDataBound

protected void list_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (string.IsNullOrEmpty(Request.QueryString["DepartmentID"]) ||
(e.Item.FindControl("hdf_DepartmentID") as HiddenField).Value.ToString() !=
Request.QueryString["DepartmentID"])
{

e.Item.FindControl("CategoriesList1").Visible = false;

}
}


- Tạo trang Catalog.aspx và test project
Phát tri

n

ng d

ng Web ASP.NET


08CDITEC

2010


17

Nguyễn Phạm Phương Nam - Bộ môn CNPM – Khoa CNTT - DHKHTN


3.2 List of Products
- Tạo User Control ProductsList.ascx
- Thành phần GUI
<asp:Label ID="pagingLabel" runat="server" CssClass="PagingText"

Visible="false" />
&nbsp;&nbsp;
<asp:HyperLink ID="previousLink" runat="server" CssClass="PagingText"
Visible="false">Previous</asp:HyperLink>
&nbsp;&nbsp;
<asp:HyperLink ID="nextLink" runat="server" CssClass="PagingText"
Visible="false">Next</asp:HyperLink>

<asp:DataList ID="list" runat="server" RepeatColumns="2">
<ItemTemplate>
<table cellpadding="0" align="left">
<tr height="105">
<td align="center" width="110">
<a href='Product.aspx?ProductID=<%# Eval("ProductID")%>'>
<img width="100" src='ProductImages/<%#
Eval("Image1FileName") %>' border="0" />
</a>
</td>
<td valign="top" width="250">
<a class="ProductName" href='Product.aspx?ProductID= <%#
Eval("ProductID")%>'>
<%# Eval("Name") %>
</a>
<br />
<span class="ProductDescription">
<%# Eval("Description") %>
<br />
<br />
Price: </span><span class="ProductPrice">
<%# Eval("Price", "{0:c}") %>

</span>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>

- Thành phần code
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
Phát tri

n

ng d

ng Web ASP.NET


08CDITEC

2010


18


Trần Phượng Hoàng – PTN BMCNPM – Khoa CNTT – DHKHTN

using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Specialized;

public partial class UserControls_ProductsList : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
PopulateControls();

}
private void PopulateControls()
{
// Retrieve DepartmentID from the query string
string departmentId = Request.QueryString["DepartmentID"];
// Retrieve CategoryID from the query string
string categoryId = Request.QueryString["CategoryID"];
// Retrieve Page from the query string
string page = Request.QueryString["Page"];
if (page == null) page = "1";
// How many pages of products?
int howManyPages = 1;
// If browsing a category
if (categoryId != null)
{
// Retrieve list of products in a category

list.DataSource =
CatalogAccess.GetProductsInCategory(categoryId, page, out
howManyPages);
list.DataBind();
}
else if (departmentId != null)
{
// Retrieve list of products on department promotion
list.DataSource = CatalogAccess.GetProductsOnDepartmentPromotion
(departmentId, page, out howManyPages);
list.DataBind();
}
else
{
// Retrieve list of products on catalog promotion
list.DataSource =
CatalogAccess.GetProductsOnCatalogPromotion(page, out
howManyPages);
list.DataBind();
}
// display paging controls
if (howManyPages > 1)
{
// have the current page as integer
int currentPage = Int32.Parse(page);
// make controls visible
pagingLabel.Visible = true;
previousLink.Visible = true;
Phát tri


n

ng d

ng Web ASP.NET


08CDITEC

2010


19

Nguyễn Phạm Phương Nam - Bộ môn CNPM – Khoa CNTT - DHKHTN

nextLink.Visible = true;
// set the paging text
pagingLabel.Text = "Page " + page + " of " +
howManyPages.ToString();
// create the Previous link
if (currentPage == 1)
previousLink.Enabled = false;
else
{
NameValueCollection query = Request.QueryString;
string paramName, newQueryString = "?";
for (int i = 0; i < query.Count; i++)
if (query.AllKeys[i] != null)
if ((paramName =

query.AllKeys[i].ToString()).ToUpper() != "PAGE")
newQueryString += paramName + "=" + query[i] +
"&";
previousLink.NavigateUrl = Request.Url.AbsolutePath +
newQueryString
+ "Page=" + (currentPage - 1).ToString();
}
// create the Next link
if (currentPage == howManyPages)
nextLink.Enabled = false;
else
{
NameValueCollection query = Request.QueryString;
string paramName, newQueryString = "?";
for (int i = 0; i < query.Count; i++)
if (query.AllKeys[i] != null)
if ((paramName =
query.AllKeys[i].ToString()).ToUpper() != "PAGE")
newQueryString += paramName + "=" + query[i] +
"&";
nextLink.NavigateUrl = Request.Url.AbsolutePath +
newQueryString +
"Page=" + (currentPage + 1).ToString();
}
}
}

}

- Tạo thư mục ProductImage và copy hình ảnh vào

3.3 Catalog.aspx
- Thành phần GUI
<asp:Content ID="Content2" ContentPlaceHolderID="contentPlaceHolder"
Runat="Server">
<br />
<asp:Label ID="catalogTitleLabel" CssClass="CatalogTitle"
Phát tri

n

ng d

ng Web ASP.NET


08CDITEC

2010


20

Trần Phượng Hoàng – PTN BMCNPM – Khoa CNTT – DHKHTN

Runat="server" />
<br />
<br />
<asp:Label ID="catalogDescriptionLabel" CssClass="CatalogDescription"
Runat="server" />
<br />

<br />
<br />
<br />
</asp:Content>
- Kéo thả ProductList.ascx vào thành phần Catalog.aspx (theo hướng dẫn)
- Thành phần code
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class Catalog : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PopulateControls();

}

// Fill the page with data
private void PopulateControls()
{
// Retrieve DepartmentID from the query string
string departmentId = Request.QueryString["DepartmentID"];

// Retrieve CategoryID from the query string
string categoryId = Request.QueryString["CategoryID"];

// If browsing a category
if (categoryId != null)
{
// Retrieve category details and display them
CategoryDetails cd =
CatalogAccess.GetCategoryDetails(categoryId);
catalogTitleLabel.Text = cd.Name;
catalogDescriptionLabel.Text = cd.Description;
// Set the title of the page
this.Title = BalloonShopConfiguration.SiteName +
" : Category : " + cd.Name;
}
// If browsing a department
else if (departmentId != null)
Phát tri

n

ng d

ng Web ASP.NET


08CDITEC

2010



21

Nguyễn Phạm Phương Nam - Bộ môn CNPM – Khoa CNTT - DHKHTN

{
// Retrieve department details and display them
DepartmentDetails dd =
CatalogAccess.GetDepartmentDetails(departmentId);
catalogTitleLabel.Text = dd.Name;
catalogDescriptionLabel.Text = dd.Description;
// Set the title of the page
this.Title = BalloonShopConfiguration.SiteName +
" : Department : " + dd.Name;
}
}
}
-
3.4 Product.aspx
- Thành phần GUI
<asp:Content ID="Content2" ContentPlaceHolderID="contentPlaceHolder"
runat="Server">
<br />
<asp:Label CssClass="ProductTitle" ID="titleLabel" runat="server"
Text="Label"></asp:Label>
<br />
<br />
<asp:Image ID="productImage" runat="server" />
<br />
<asp:Label CssClass="ProductDescription" ID="descriptionLabel"

runat="server" Text="Label"></asp:Label>
<br />
<br />
<span class="ProductDescription">Price:</span>&nbsp;
<asp:Label CssClass="ProductPrice" ID="priceLabel" runat="server"
Text="Label"></asp:Label>
<br />
<br />
</asp:Content>

- Thành phần Code
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class Product : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
Phát tri

n

ng d


ng Web ASP.NET


08CDITEC

2010


22

Trần Phượng Hoàng – PTN BMCNPM – Khoa CNTT – DHKHTN

{
PopulateControls();

}

// Fill the control with data
private void PopulateControls()
{
// Retrieve ProductID from the query string
string productId = Request.QueryString["ProductID"];
// stores product details
ProductDetails pd;
// Retrieve product details
pd = CatalogAccess.GetProductDetails(productId);
// Display product details
titleLabel.Text = pd.Name;
descriptionLabel.Text = pd.Description;

priceLabel.Text = String.Format("{0:c}", pd.Price);
productImage.ImageUrl = "ProductImages/" + pd.Image2FileName;
// Set the title of the page
this.Title = BalloonShopConfiguration.SiteName +
" : Product : " + pd.Name;
}
}

3.5 Mở rộng Default.aspx
- Kéo thả User Control ProductsList vào trang này (theo hướng dẫn)
- Test project


Hết

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×