bÀi tẬp asp

55
BÀI TẬP ASP.NET Lưu ý : qui định đặt tên cho các file phải tuân thủ theo vì liên quan đến việc hướng dẫn làm bài tập và hướng dẫn viết code trong chương trình. Bài 1: (Thiết lập Webserver) Tạo 1 trang Helloworld.aspx như sau” Bước 1: Mở VS.Net tạo trang ASP.Net Website: bt1 Chọn Location: File System Bước 2: 1

Upload: connectshares

Post on 30-Mar-2015

654 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: BÀI  TẬP ASP

BÀI TẬP ASP.NETLưu ý: qui định đặt tên cho các file phải tuân thủ theo vì liên quan đến việc hướng dẫn làm bài tập và hướng dẫn viết code trong chương trình.Bài 1: (Thiết lập Webserver)Tạo 1 trang Helloworld.aspx như sau”Bước 1:

Mở VS.Net tạo trang ASP.Net Website: bt1Chọn Location: File System

Bước 2:

Bước 3:Thực thi trang Default.aspx

1

Page 2: BÀI  TẬP ASP

Cách 1: Biên dịch trực tiếp trên Visual .Net 2005 (F5).Cách 2: Hãy thiết lập WebServer cho Website(đặt tên ứng dụng tùy ý ví dụ

bt_asp) sau: (Tạo thư mục ảo trên Web Server: IIS)

a) Thiết lập website bt_asp tham chiếu đến folder bt1. Thiết lập trang mặc định là Default.aspx. Sau đó mở trình duyệt IE nhập vào địa chỉ sau và xem kết quả:

Trường hợp 1: http://localhost/bt_asp sau đó nhấn EnterTrường hợp 2: http://tenserver/bt_asp sau đó nhấn Enter (tenserver chính là

computerName của máy chứa website)Trường hợp 3: http://tenserver/bt_asp/Default.aspx sau đó nhấn Enter (tenserver

chính là computerName của máy chứa website)Bài 2:

Bước 1: Yêu cầu tạo 1 tập tin CSS tên stylesheet.css (Màu nền, màu chữ, font chữ).

Bước 2: Mở lại Web site bt1, add thêm 1 trang bt11.html như sau, sau đó nhúng tập tin stylesheet.css vừa tạo vào trang bt11.html

Bước 3: Mở bt11.html đổi tên bt11.aspx. Thêm dòng code sau vào đầu trang<%@ Page Language="C#"%>

2

Page 3: BÀI  TẬP ASP

Nhập đoạn code inline sau:

Bài 3:Tạo Web site Baitap3 gồm các file: Default.aspx, CheckUser.aspx, News.aspx.Trang Default.aspx có giao diện:

3

<head> <title>Untitled Page</title> <link href="stylesheet.css" rel="stylesheet" type="text/css" /></head><body><% string name1 = "Nguyễn Thành Nhân", name2 = "Trương ThịThanh Thuỷ", name3 = "Trần Minh Nhật", name4="Minh Long";%><table border="1" width="49%" id="table1">

<tr><td align="center"><p align="center">Tên SV</td>

</tr><tr>

<td align="center"><%=name1 %></td></tr><tr>

<td align="center"><%=name2 %></td></tr><tr>

<td align="center"><%=name3 %></td></tr><tr>

<td align="center"><%=name4 %></td></tr>

</table></body>

Page 4: BÀI  TẬP ASP

Trang CheckUser.aspx.

4

<body> <form method="Get" action="CheckUser.aspx">

<!--webbot bot="SaveResults" U-File="fpweb:///_private/form_results.csv" S-Format="TEXT/CSV" S-Label-Fields="TRUE" -->

<table border="1" width="100%" id="table1"><tr>

<td style="text-align: center" colspan="2"> <strong><span style="font-size: 14pt">&nbsp; Đăng Ký Thành Viên</span></strong></td>

</tr><tr>

<td style="width: 148px; text-align: right">User</td><td><input type="text" name="txtUser" size="20" style="font-family:

Tahoma; font-size: 10pt; color: #0000FF; font-weight: bold"></td></tr><tr>

<td style="width: 148px; text-align: right">Password</td><td><input type="password" name="txtPwd" size="20"></td>

</tr><tr>

<td style="width: 148px">&nbsp;</td><td><input type="submit" value="Gui" name="B1"></td>

</tr></table>

</form>

<a href="News.aspx>Tin tuc</a><br /><a href="News.aspx>Music</a><br />

</body>

Page 5: BÀI  TẬP ASP

Trang News.aspx

5

<body> <% String strUser, strPwd; strUser= Request.QueryString["txtUser"]; strPwd = Request.QueryString["txtPwd"];

HttpCookie varCK = new HttpCookie("ckInfor"); varCK["us"] = strUser; varCK["pwd"] = strPwd; Response.Cookies.Add(varCK); %> <table border="1" width="100%" id="table1">

<tr><td style="text-align: center" colspan="2">

<strong><span style="font-size: 14pt">&nbsp; Thông Tin của Thành Viên</span></strong></td>

</tr><tr>

<td style="width: 211px">Ten</td><td style="width: 367px">

Mat khau</td></tr><tr>

<td style="font-family: Tahoma; font-size: 10pt; color: #0000FF; font-weight: bold; width: 211px;">

<%=strUser %></td><td style="font-family: Tahoma; font-size: 10pt; color: #0000FF; font-

weight: bold; width: 367px;"><%=strPwd %></td>

</tr></table></body>

Page 6: BÀI  TẬP ASP

6

<body><% Boolean bl; bl =Convert.ToBoolean( Request.Cookies["permit"].Value); if (bl == true) { %> <%String strID, strType; strID = Request.QueryString["Id"]; strType = Request.QueryString["type"]; %> Ban chon ma so:<%=strID%><br /> Kieu hien thi:<%=strType%><br /> <%String strckUser, strckPwd; strckUser = Request.Cookies["ckInfor"]["us"]; strckPwd = Request.Cookies["ckInfor"]["pwd"]; %> User la:<%=strckUser%> <br/> password:<%=strckPwd%> <%} else Response.Redirect("Default.aspx"); %></body>

<a href="News.aspx?Id=123&type=show">Tin tuc</a><br /><a href="News.aspx?Id=36586&type=item">Music</a><br />

Truyền tham biến Id, type bằng QueryString trong trang CheckUser.aspx

if (strUser == "abc") { HttpCookie ckPermit = new HttpCookie("permit"); ckPermit.Value = "true"; Response.Cookies.Add(ckPermit); } else { HttpCookie ckPermit = new HttpCookie("permit"); ckPermit.Value = "false"; Response.Cookies.Add(ckPermit); }

Page 7: BÀI  TẬP ASP

Bài 4:Tạo Website Baitap4 gồm các trang:

Thiết kế 3 trang : Login.aspx , CheckUser.aspx , Infor.aspx Khi nhấn nút Login ở trang Login thì chuyển sang trang CheckUser để ktra

dữ liệu : nếu user là xyz và password là 123 thì lưu xuống 2 cookie và gọi trang Infor :

Một cookie userCk 2 chiều : “us” = xyz và “pwd”= 123 Một cookie permit 1 chiều chứa trị True

Sơ đồ thực thi của ứng dụng

Nếu nhập sai sẽ quay lại trang Login

7

Page 8: BÀI  TẬP ASP

Nếu nhập đúng userName và Password thì vào trang Infor (nội dung tùy ý)

8

Page 9: BÀI  TẬP ASP

9

// trang Login.aspx <form method="POST" action="checkUser.aspx"><table border="1" width="469" height="25"><tr>

<td height="25" width="172">user</td><td height="25" width="281"><input type="text" name="txtUser" size="20"></td></tr>

<tr><td height="25" width="172">Password</td><td height="25" width="281"><input type="text" name="txtPwd" size="20"></td></tr>

<tr><td height="25" width="469" colspan="2"><input type="submit" value="Login" name="B1"></td></tr>

</table></form><%String var1; var1 = "1";

var1 = Request.QueryString["th"]; if(var1 == "59"){ %> nhap sai username va password <%} %>

//trang CheckUser.asp<% string strUser, strPwd; strUser = Request.Form["txtUser"]; strPwd = Request.Form["txtPwd"];HttpCookie varCk = new HttpCookie("userCK");HttpCookie varPermit = new HttpCookie("permit");//biến này được dùng như cờvarCk["us"] = "";varCk["pwd"] = "";varPermit.Value ="false"; if ((strUser == "xyz") && (strPwd == "123")) { varPermit.Value ="true"; varCk["us"] = strUser; varCk["pwd"] = strPwd; Response.Cookies.Add(varCk); Response.Cookies.Add(varPermit); Response.Redirect("Infor.aspx"); } else {

Response.Cookies.Add(varCk);Response.Cookies.Add(varPermit);Response.Redirect("Login.aspx?th = 1");

} %>

Page 10: BÀI  TẬP ASP

10

//trang Infor.aspx<% try

{ String strPermit;

strPermit = Request.Cookies["permit"].Value; if (strPermit == "true")

{%>

// hienthiPage (nhấn F3 để xem)<%

} else

Response.Redirect("Login.aspx"); }

catch (Exception ex) { Response.Redirect("Login.aspx"); }

%>

Page 11: BÀI  TẬP ASP

Bài 5: HTML Server Controls Thiết kế form như sau: (Viết bằng 2 cách Code Inline & Behide)

….<script runat="server"> void Nhap(object sender, EventArgs e) { MaSV.InnerHtml = txtTen.Value; MaMH.InnerHtml = drpMH.Value; diem.InnerHtml = txtDiem.Value; } </script>…

11

Code Inline

protected void Nhap_ServerClick(object sender, EventArgs e) { MaSV.InnerHtml = txtTen.Value; MaMH.InnerHtml = drpMH.Value; diem.InnerHtml = txtDiem.Value;

}

Code Behide

Page 12: BÀI  TẬP ASP

12

protected void Button1_Click(object sender, EventArgs e){

FileName.InnerHtml = FileUpload1.PostedFile.FileName;ContentType.InnerHtml = FileUpload1.PostedFile.ContentType;ContentLength.InnerHtml = FileUpload1.PostedFile.ContentLength.ToString();string path = FileUpload1.PostedFile.FileName.ToString();string[] filename = path.Split('\\');string fname;fname = filename[filename.Length - 1];FileUpload1.PostedFile.SaveAs(Server.MapPath("") + "\\UloadFiles" + fname);

}

Page 13: BÀI  TẬP ASP

Bài 6: Web Server ControlsDùng các công cụ là Web Server Controls khi user bấm vào Them thì dữ liệu được chuyển sang trang Dangky.aspx

13

Page 14: BÀI  TẬP ASP

Bài 7: Kiểm tra lỗi dữ liệu nhậpYêu cầu:

Thiết kế Web Form như sau:- Họ và tên: Không rỗng- Số tài khoản: Là dữ liệu số, có 12 số- Email: có dạng ten_user@ten_domain- Thành phố: Phải được chọn- Năm sinh: từ 1900 1990- Vốn điều lệ: >= 20 tỉNếu dữ liệu hợp lệ thì click nút Đăng ký xuất hiện thông báo “Đăng ký thành công”.Ngược lại: Trở lại trang Dangky.aspx

14

Page 15: BÀI  TẬP ASP

Bài 8: Master PageThiết kế templateTạo một Folder tên là YourNameTemplate trên ổ đĩa làm việc. Trong YourNameTemplate tạo folder con là images(lên mạng download hình và chép vào folder images này để có hình thiết kế ). Các bài tập sau đều lưu vào YourNameTemplatea) Thiết kế trang web sau(lưu với tên là DesignTemplate.htm):

Hướng dẫn thiết kế(xem từng bước hình sau)

Trong Bước 1: tạo bảng gồm có 3 dòng(chỉnh border của table=0 và định dạng các ô có chế độ valign là top) sau đó đưa chuột vào phần 2 xoá đi “phần 2” và insert thêm một bảng 1 dòng 3 cột và chỉnh sửa độ rộng cột tướng xứng (phần 21 và 23 thì nhỏ). Trong bảng này vẫn để border của table là 1 và chỉnh sửa bordercolor của bảng cho phù hợp. Thiếp lập cellpadding và cellspaceing đều là 1 và định dạng valign của các ô đều là top.

15

Page 16: BÀI  TẬP ASP

Sau đó đưa chuột vào phần 22 và xoá đi và thêm vào một bảng chỉ có 1 dòng và một cột. Định dạng border bảng này là 0 cellspacing và cellpadding đều là 4. Lưu ý: phải gõ chữ vào như đã ghi trong bảng thiết kế.

b) Thiết kế trang sau(lưu với tên là banner.htm)

b) Thiết kế trang sau(lưu với tên là bottom.htm):

c) Thiết kế trang sau (lưu với tên là left.htm):

16

e) Thiết kế trang sau (lưu với tên là right.htm):

Page 17: BÀI  TẬP ASP

Tạo Project WebsiteTạo một Project Webiste tên là Infor lưu vào folder YourNameTemplate. Sau đó copy folder images trong folder YourNameTemplate vào folder Infor.a) Tạo các file include

- Mở file banner.htm lên và mở khởi động NotePad . Copy source code (chỉ copy những gì chưá trong cặp thẻ Body) của file banner.htm rồi Paste vào NotePad rồi lữu lại tên là Banner.inc vào folder Infor.

- Tương tự ta copy phần Body của trang bottom.htm và lưu lại tên là bottom.inc vào folder Infor.

- Copy phần body của trang left.htm và lưu lại thành là left.inc trong folder Infor.- Copy phần body của trang right.htm và lưu lại thành right.aspx vào folder Infor.

b) Thêm 1 file mới và đặt tên file này là TemplateMaster.aspx (click phải vào project Infor->Add New Item…->Chọn WebForm->Gõ vào ô Name: TemplateMaster.aspx->bấm nút Add)

c) Thêm1 file Cascading style sheet (cách làm giống câu b nhưng chọn loại tập tin là Style Sheet) rồi trong ô Name đặt tên là FormatClient.css->Add

d) Thêm1 file JavaScript (cách làm giống câu b nhưng chọn loại tập tin là Jscript file) rồi trong ô Name đặt tên là ProcessClient.js->Add

e) Mở source code của file TemplateMaster.aspx ra(bấm vào nút Source)

17

Page 18: BÀI  TẬP ASP

Xoá đi các đọan code chứa trong thẻ Body (tức là bỏ đi từ thẻ <form>…</form>) và thẻ DOCTYPESửa lại dữ liệu chưá trong cặp thẻ title (dữ liệu văn bản tùy ý)Sau câu lệnh

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TemplateMaster.aspx.cs" Inherits="TemplateMaster" %>

Gõ 2 câu lệnh sau (thêm vào không gian tên để sử dụng kết nối DataBase)<%@import Namespace="System.Data"%>

% @import Namespace="System.Data.OleDb" % >Sau cặp thẻ <title></title> gõ 2 câu lệnh sau:

<link type="text/css" href="FormatClient.css" rel="stylesheet" />

<script type="text/javascript" src="ProcessClient.js"></script>

Mở tập tin DesignTemplate.htm copy những gì chứa trong thẻ Body sau đó Paste vào sau thẻ Body của tập tin TemplateMaster.aspx. Sau đó thay thế các vị trí sau:+ Xoá chữ Phần 1 thế bằng câu lệnh sau:<!--#include file="banner.inc"-->+ Xoá chữ Phần 21 thế bằng câu lệnh sau:<!--#include file="left.inc"-->+ Xoá chữ Phần 221 thế bằng câu lệnh sau: <!--Begin Content--> Content <!---End Content->+ Xoá chữ Phần 23 thế bằng câu lệnh sau:<!--#include file="right.aspx"-->

18

Page 19: BÀI  TẬP ASP

+ Xoá chữ Phần 3 thế bằng câu lệnh sau:<!--#include file="bottom.inc"-->Sau đó lưu lại. Sau đó biên dịch chương trình và chạy trang TemplateMaster.aspx(Sẽ xuất hiện như trang sau). Nếu như trang của bạn hiển thị không giống trang sau thì hãy chỉnh sửa đến khi nào giống rồi mới tiếp tục các bài tập tiếp theo

f) Thêm 1 file aspx và đặt tên cho file này là Default.aspx . Sau đó mở source code file này sau chỉ thị @Page ta xoá hết code trên file này(chỉ để lại chỉ thị @Page). Sau đó copy tất cả các source code(bỏ dòng @Page) file TemplateMaster.aspx rồi paste vào sau dòng lệnh @Page của trang Default.aspx. Sau đó trên file Default.aspx tại chữ Content (Chưá trong: <!--Begin Content--> Content <!---End Content->) thêm vào một câu lệnh chèn hình rồi lưu và hiển thị trang Default.aspx như sau:

19

Page 20: BÀI  TẬP ASP

g) Mở file left.inc tạo liên kết cho trang chủ link đến trang Default.aspx và lưu lại.h) Thêm 1 file aspx và đặt tên cho file này là CustomerNews.aspx có giao diện như

sau:

Mở file left.inc tạo liên kết cho “Tin tức khách hàng” link đến trang Customer.aspx và lưu lại

i) Thêm 1 file aspx và đặt tên cho file này là ListNews.aspx có giao diện như sau:

20

Page 21: BÀI  TẬP ASP

Mở file left.inc tạo liên kết cho “Tin tức ” link đến trang ListNews.aspx và lưu lạij) Thêm 1 file aspx và đặt tên cho file này là ListCustomer.aspx có giao diện như

sau:

21

Page 22: BÀI  TẬP ASP

Mở file left.inc tạo liên kết cho “Khách hàng ” link đến trang ListCustomer.aspx và lưu lại

k) Thêm 1 file aspx và đặt tên cho file này là ListProduct.aspx có giao diện như sau:

Mở file left.inc tạo liên kết cho “Sản phẩm ” link đến trang ListProduct.aspx và lưu lạil) Thêm 1 file aspx và đặt tên cho file này là InsertNewsCustomer.aspx có giao diện

như sau:

22

Page 23: BÀI  TẬP ASP

Nút Reset khi bấm vào là xoá dữ liệu trên form. Còn nút “Thêm” khi bấm vào là gửi dữ liệu qua trang InsertDataNewsCustomer.aspx (Nghĩa là nút Thêm phải là Submit và trong tag Form thuộc tính action=”InsertDataNewsCustomer.aspx ” )Mở file left.inc tạo liên kết cho “Thêm tin tức KH ” link đến trang InsertDataNewsCustomer.aspx và lưu lại

m) Thêm 1 file aspx và đặt tên cho file này là InsertDataNewsCustomer.aspx có giao diện như sau:

n) Thêm một file aspx và đặt tên cho file này là Exercise1.aspx có giao diện như sau:

Lưu ý: đặt tên cho control text Username là txtUser, control password là txtPwd, control Authority là radAuthor (nút khách có giá trị là guest, nút Thành viên có giá trị là member và nút Quản trị có giá trị là Admin) . Thuộc tính action của form có giá trị là Exercise1TransferData.aspx và Method của form có giá trị là Post.Mở file left.inc tạo liên kết cho “Thực hành 1 ” link đến trang Exercise1.aspx và lưu lại

23

Page 24: BÀI  TẬP ASP

o) Thêm một file aspx và đặt tên cho file này là Exercise1TransferData.aspx có giao diện như sau:

Hãy viết chương trình lấy dữ liệu từ client gửi về từ trang Exercise1.aspx. Sau đó dữ liệu lấy được điền hiển thị vào các vị trí x,y,z.Hướng dẫn:(Nhắc lại lý thuyết muốn lấy giá trị một phần tử trên form “phần tử tên là FieldName” với method là Post ta dùngvarName=Request.Form[“FieldName”];) Sau dòng <!--Begin Content-->Ta thêm đoạn mã script ASP.Net để lấy giá trị<%

// Viết code trong đâyString strUser, strPassword, strAuthor;//code here….strUser=Request.Form[“txtUser”];//tương tự cho các trường khác

%>Sau đó tìm chữ “x” xóa đi và thế bằng <%=strUser%> tương tự cho các vị trí “y” và “z”.

p) Hãy mở source code HTML của file InsertNewsCustomer.aspx và đặt tên cho các control text và textArea. Sau đó mở InsertDataNewsCustomer.aspx viết code ASP.Net để lấy dữ liệu từ trang InsertNewsCustomer.aspx gửi về và hiển thị dữ liệu lên trang .Hướng dẫn:Làm giống như câu trên rồi cũng tìm chữ Title và Content thế bằng lệnh <%=varName%>. với varName là biến lưu trữ dữ liệu tương ứng.

q) Thêm một file aspx và đặt tên cho file này là Exercise2.aspx có giao diện như sau:

24

Page 25: BÀI  TẬP ASP

Lưu ý:Giới tính: lần lượt có giá trị là male và femaleHộ khẩu : lần lượt có các cặp giá trị sau:

Text ValueTP Hồ Chí Minh Ho Chi Minh cityTiền Giang Tien Giang ProvinceTP Hải Phòng Hai Phong cityBình Dương Binh Duong Province

Ngoại ngữ: lần lượt có giá trị: English , French , Chinese Đăng ký là nút Submit. Thuộc tính action của form có giá trị là Exercise2TransferData.aspx và Method=”Post”.

r) Thêm một file aspx và đặt tên cho file này là Exercise2TransferData.aspx có giao diện như sau:

25

Page 26: BÀI  TẬP ASP

Viết chương trình lấy dữ liệu từ trang Exercise2.aspx và hiển thị vào các vị trí 1,2,3,4,5,6 tương ứng.

s) Thêm một file aspx và đặt tên cho file này là ExerciseProduct.aspx có giao diện như sau:

Ở các link Mua link đến trang SaveCart.aspx và truyền vào 2 tham số mà ProductID và ProductName có giá trị tương ứng là Mã sản phẩm và Tên sản phẩm

26

Page 27: BÀI  TẬP ASP

Ví dụ<a href=”SaveCart.aspx?ProductID=P078&ProductName=M78”>Mua<a/>Dùng Session hãy lưu trữ các mặt hàng mà người sử dụng đã mua(nghĩa là khi bấm vào Mua là lưu).Mở file left.inc thêm dòng “Thực hành 3” và link đến trang ExerciseProduct.aspx . Sau đó lưu lại.

t) Thêm một file aspx và đặt tên cho file này là ShoppingCart.aspx dùng để hiển thị các mặt hàng mà người sử dụng đã chọn có giao diện như sau:

Link Tính tiền liên kết đến trang CommitShopping.aspx(Trang này hủy tất cả các dữ liệu của phiên làm việc nghĩa là xóa dữ liệu trong Session). Link Mua tiếp link đến trang ExerciseProduct.aspx .Mở file left.inc thêm dòng “Giỏ hàng” link đến trang ShoppingCart.aspx sau đó lưu lại.

u) Thêm một file aspx và đặt tên cho file này là AddProduct.aspx dùng để hiển thị các mặt hàng mà người sử dụng đã chọn có giao diện như sau:

27

Page 28: BÀI  TẬP ASP

Khi bấm vào nút Thêm thì dữ liệu gửi đến trang InsertProduct.aspx và trang này hiển thị như sau:

Nhập tiếp: sẽ link đến trang AddProduct.aspx.Mở file left.inc dòng “Nhập sản phẩm” và link đến trang AddProduct.aspx và lưu lại.

28

Page 29: BÀI  TẬP ASP

Bài 9: ADO Kết nối dữ liệu (DataReader)Lấy dữ liệu từ bảng Categories. Hiển thị dữ liệu của các field:Loại sản phẩm (CategoryName) và Mô tả (Description) lên table như hình dưới đây

Hướng dẫn:Tạo 1 file mới tên là DataReader_Table_Categories.aspx. Trong đó có một labelvới id=lblCategoriesXử lý trong DataReader_Table_Categories.aspx.cs- Imports Namespaces

using System.Data;using System.Data.SqlClient;

- Khai báo các biến toàn cụcstring ConStr, SqlStr;

SqlConnection ConObj;SqlDataReader dr;

- Viết hàm mở và đóng kết nối.//mo ket noiBoolean Open_Database(){Boolean flag = false;try{ConStr = Application["strCon"].ToString();ConObj = new SqlConnection(ConStr);

29

Page 30: BÀI  TẬP ASP

ConObj.Open();flag = true;}catch (Exception e){lblCategories.Text = "Xảy ra lỗi khi mở kết nối" +e.Message;}return flag;}//đóng ket noiBoolean Close_Database(){Boolean flag = false;try{ConObj.Close();flag=true;}catch(Exception e){lblCategories.Text = "Xảy ra lỗi khi đóng kết nối"+ e.Message;}return flag;}

Viết hàm GetCategories để lấy dữ liệu và ShowCategories hiển thị dữ liệu từbảng Categories lên trang Web//Lấy dữ liệu từ bảng Categories

Boolean GetCategories(){Boolean flag = false;SqlCommand cmd;//mo ket noiif (!Open_Database())//khong mo duoc ket noi

return flag;

//lay du lieutry{SqlStr = "Select * from Categories";cmd = new SqlCommand(SqlStr);cmd.Connection = ConObj;dr = cmd.ExecuteReader();flag= true;}catch (Exception e){

30

Page 31: BÀI  TẬP ASP

tdCate.InnerText = "Xảy ra lỗi khi truy cập dữliệu " + e.Message;Close_Database();}return flag;}//Hiển thị dữ liệu của bảng Categories lên tableBoolean ShowCategories(){Boolean flag = false;string str = "";if (!GetCategories())//khong lay duoc du lieureturn flag;//hien thi du lieutry{str += "<table border='1' cellspacing='0'align='center' width='90%'><tr><td>Tên Loại</td><td>Môtả</td></tr>";while (dr.Read()){str += "<tr>";str += "<td>";str += dr["CategoryID"].ToString();str += "</td>";str += "<td>";str += dr["CategoryName"].ToString();str += "</td>";str += "</tr>";}str += "</table>";tdCate.InnerHtml = str;//hien thi du lieu len<td>flag = true;

}

31

Page 32: BÀI  TẬP ASP

ADO Kết nối dữ liệu (DataSet) - Tạo class trong App-Code (Thực hiện kết nối Database)

32

public class DatabaseSqlServer{ SqlConnection ConObj;

public DatabaseSqlServer(){

string ConStr = ConfigurationManager.AppSettings["ConnectionString"]; ConObj = new SqlConnection(ConStr);

} public Boolean Open_Database() { Boolean rt=true; try { ConObj.Open(); rt = true; } catch { rt= false; } return rt; } public Boolean Close_Database() { Boolean rt = true; try { ConObj.Close(); rt = true; } catch { } return rt; } public DataTable loadDataTable(string SqlStr) { Open_Database();//ktra mo duoc khong //try catch SqlDataAdapter da = new SqlDataAdapter(SqlStr, ConObj); DataSet ds = new DataSet(); da.Fill(ds); Close_Database(); return ds.Tables[0]; }}

Page 33: BÀI  TẬP ASP

Tạo 1 trang Master Page:

33

Default.aspx

Tính tiền

Buy.aspx

Mua tiếpDefault.aspx

Bill.aspx

Mua

Page 34: BÀI  TẬP ASP

Default.aspx

using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { string SqlStr = "Select * from products, suppliers where products.supplierID=suppliers.supplierID"; ShowData(SqlStr); } public DataTable GetData(string SqlStr) { DatabaseSqlServer slc = new DatabaseSqlServer(); DatabaseSqlServer cls = new DatabaseSqlServer(); DataTable dt = cls.loadDataTable(SqlStr); return dt; } public void ShowData(string SqlStr) { string vCatName=Request.QueryString["sCatName"]; DataTable dt = GetData(SqlStr); string str = "<table align='center' width='95%'>"; str += "<tr>";

34

Page 35: BÀI  TẬP ASP

str += "<td colspan='3' align='center' class='title'>Danh sách sản phẩm</td>"; str += "</tr>";

str += "<tr>"; str += "<td>Tên sản phẩm"; str += "</td>"; str += "<td>Nhà cung cấp"; str += "</td>"; str += "<td>Giá"; str += "</td>"; str += "<td>Mua"; str += "</td>"; str += "</tr>";

int n = Convert.ToInt32(dt.Rows.Count); for (int i = 0; i < n; i++) { str += "<tr>"; str += "<td>"; str += dt.Rows[i]["productName"]; str += "</td>"; str += "<td>"; str += dt.Rows[i]["CompanyName"]; str += "</td>"; str += "<td>"; str += dt.Rows[i]["UnitPrice"]; str += "</td>"; str += "<td>"; str += "<a href='Buy.aspx?sProID=" + dt.Rows[i]["ProductID"] + "'>Mua</a>"; str += "</td>"; str += "</tr>"; } str += "</table>"; lblShowProducts.Text = str; }}

35

Page 36: BÀI  TẬP ASP

Buy.aspx

using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { string vProID = Request.QueryString["sProID"]; Session["Products"] += vProID + "@"; Label1.Text = "Bạn vừa chọn mua sản phẩm có mã là " + vProID; }

} protected void btnMuaTiep_Click(object sender, EventArgs e) { Response.Redirect("Default.aspx"); } protected void btnTinhTien_Click(object sender, EventArgs e) { Response.Redirect("Bill.aspx"); }}

36

Page 37: BÀI  TẬP ASP

Bill.aspx

using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page{

protected void Page_Load(object sender, EventArgs e) { ShowInfor(); } public void ShowInfor() {string vProducts;try{ //Lay cac san pham ma user da mua duoc luu tren session vProducts = Session["Products"].ToString();}catch{ Label1.Text = "<center><br/>Bạn chưa chọn mua sản phẩm nào. Xin vui lòng chọn mua rồi mới tính tiền!</center>"; return;

37

Page 38: BÀI  TẬP ASP

}string[] arrProducts = vProducts.Split('@');//tach chuoi//kiem tra neu user chua mua san pham naoint len = arrProducts.Length;//len-1 la so san pham user da mua//cau truy vanstring SqlStr = "Select ProductName, UnitPrice from Products where ProductId in (";for (int i = 0; i < len - 1; i++){ if (i == arrProducts.Length - 2)//neu i la san pham cuoi cung SqlStr += arrProducts[i]; else SqlStr += arrProducts[i] + ",";}SqlStr += ")";

//thuc thi cau truy vanDatabaseSqlServer cls = new DatabaseSqlServer();DataTable dt = cls.loadDataTable(SqlStr);

//Xuất ĐƠN ĐẶT HÀNGint NumberOfRecords = dt.Rows.Count;//so san pham double sum = 0;//tổng tiền;string str = "<table><tr><th colspan='4' align='center' class='title'>ĐƠN ĐẶT HÀNG</th></tr><tr><td colspan='4' align='center'><i>Tên KH: ....................</i></td></tr><tr><td colspan='4' align='center'><i>Địa chỉ: ....................</i></td></tr><tr><th align='left'>Tên sản phẩm</th><th align='right'>Đơn giá</th><th align='right'>Số lượng</th><th align='right'>Thành tiền</th></tr>";for (int i = 0; i < NumberOfRecords; i++){ str += "<tr>";

str += "<td width='250'>"; str += dt.Rows[i]["ProductName"]; str += "</td>";

str += "<td align='right' width='95'>"; double vPrice = Convert.ToDouble(dt.Rows[i]["UnitPrice"]); str += vPrice.ToString(); str += "</td>"; int vNumber = 1;//ban dau cho so luong la 1, sau do co the thay the bang textbox, cho user nhap so luong str += "<td align='right' width='75'>"; str += vNumber.ToString(); str += "</td>";

double total = vPrice * vNumber;//thành tiền str += "<td align='right' width='95'>"; str += total; str += "</td>";

sum += total;//tổng tiền str += "</tr>";}

38

Page 39: BÀI  TẬP ASP

str += "<tr><th colspan='4' align='right'>" + sum.ToString() + "</th></tr>";str += "</table>";Label1.Text = str;

//Tính tiền xong thì xoá SessionSession.Clear(); }}

39

Page 40: BÀI  TẬP ASP

Bài tập tham khảo:1. BT Cookiecookie1.aspx

<html>

<script language="C#" runat="server">

void Page_Load(Object sender, EventArgs E) { if (Request.Cookies["preferences1"] == null) { HttpCookie cookie = new HttpCookie("preferences1"); cookie.Values.Add("ForeColor","black"); cookie.Values.Add("BackColor","beige"); cookie.Values.Add("LinkColor","blue"); cookie.Values.Add("FontSize","8pt"); cookie.Values.Add("FontName","Verdana"); Response.AppendCookie(cookie); } }

protected String GetStyle(String key) { HttpCookie cookie = Request.Cookies["preferences1"]; if (cookie != null) { switch (key) { case "ForeColor" : return cookie.Values["ForeColor"]; break; case "BackColor" :

40

Page 41: BÀI  TẬP ASP

return cookie.Values["BackColor"]; break; case "LinkColor" : return cookie.Values["LinkColor"]; break; case "FontSize" : return cookie.Values["FontSize"]; break; case "FontName" : return cookie.Values["FontName"]; break; } } return ""; }

</script>

<style>

body { font: <%=GetStyle("FontSize")%> <%=GetStyle("FontName")%>; background-color: <%=GetStyle("BackColor")%>; }

a { color: <%=GetStyle("LinkColor")%> }

</style>

<body style="color:<%=GetStyle("ForeColor")%>">

<h3><font face="Verdana">Storing Volatile Data with Client-Side Cookies</font></h3>

<b><a href="customize.aspx">Customize This Page</a></b><p>

Imagine some content here ...<br> Imagine some content here ...<br> Imagine some content here ...<br> Imagine some content here ...<br> Imagine some content here ...<br> Imagine some content here ...<br> Imagine some content here ...<br> Imagine some content here ...<br>

</body> </html>

41

Page 42: BÀI  TẬP ASP

customize.aspx

<html>

<script language="C#" runat="server">

void Page_Load(Object sender, EventArgs E) { if (!IsPostBack){ HttpCookie cookie = Request.Cookies["preferences1"]; ViewState["Referer"] = Request.Headers["Referer"]; if ( cookie != null ){ BackColor.Value = (String)cookie.Values["BackColor"]; ForeColor.Value = (String)cookie.Values["ForeColor"]; LinkColor.Value = (String)cookie.Values["LinkColor"]; FontSize.Value = (String)cookie.Values["FontSize"]; FontName.Value = (String)cookie.Values["FontName"]; } } }

void Submit_Click(Object sender, EventArgs E) { HttpCookie cookie = new HttpCookie("preferences1"); cookie.Values.Add("ForeColor",ForeColor.Value); cookie.Values.Add("BackColor",BackColor.Value); cookie.Values.Add("LinkColor",LinkColor.Value); cookie.Values.Add("FontSize",FontSize.Value); cookie.Values.Add("FontName",FontName.Value); Response.AppendCookie(cookie);

42

Page 43: BÀI  TẬP ASP

if ( ViewState["Referer"] != null ){ Response.Redirect(ViewState["Referer"].ToString()); } }

void Cancel_Click(Object sender, EventArgs E) { if ( ViewState["Referer"] != null ){ Response.Redirect(ViewState["Referer"].ToString()); } }

String GetStyle(String key) { HttpCookie cookie = Request.Cookies["preferences1"]; if (cookie != null) { switch (key) { case "ForeColor" : return cookie.Values["ForeColor"]; break; case "BackColor" : return cookie.Values["BackColor"]; break; case "LinkColor" : return cookie.Values["LinkColor"]; break; case "FontSize" : return cookie.Values["FontSize"]; break; case "FontName" : return cookie.Values["FontName"]; break; } } return ""; }

</script>

<style>

body { font: <%=GetStyle("FontSize")%> <%=GetStyle("FontName")%>; background-color: <%=GetStyle("BackColor")%>; }

table { font: <%=GetStyle("FontSize")%> <%=GetStyle("FontName")%>; background-color: <%=GetStyle("BackColor")%>; foreground-color: <%=GetStyle("ForeColor")%> }

43

Page 44: BÀI  TẬP ASP

a { color: <%=GetStyle("LinkColor")%> }

</style>

<body style="color:<%=GetStyle("ForeColor")%>">

<form runat="server">

<h3><font face="Verdana">Customize This Page</font></h3>

<b>Select Your Preferences: </b><p>

<table style="color:<%=GetStyle("ForeColor")%>"> <tr> <td>Background Color:</td> <td> <select id="BackColor" runat="server"> <option>beige</option> <option>yellow</option> <option>red</option> <option>blue</option> <option>lightblue</option> <option>lightgreen</option> <option>black</option> <option>white</option> </select> </td> </tr> <tr> <td>Foreground Color:</td> <td> <select id="ForeColor" runat="server"> <option>black</option> <option>beige</option> <option>yellow</option> <option>red</option> <option>blue</option> <option>lightblue</option> <option>lightgreen</option> <option>white</option> </select> </td> </tr> <tr> <td>Hyperlink Color:</td> <td> <select id="LinkColor" runat="server"> <option>blue</option> <option>beige</option> <option>yellow</option> <option>red</option> <option>lightblue</option> <option>lightgreen</option> <option>black</option> <option>white</option> </select>

44

Page 45: BÀI  TẬP ASP

</td> </tr> <tr> <td>Font Size:</td> <td> <select id="FontSize" runat="server"> <option>8pt</option> <option>10pt</option> <option>12pt</option> <option>14pt</option> </select> </td> </tr> <tr> <td>Font Name:</td> <td> <select id="FontName" runat="server"> <option>verdana</option> <option>tahoma</option> <option>arial</option> <option>times</option> </select> </td> </tr> </table>

<p>

<input type="submit" OnServerClick="Cancel_Click" Value="Cancel" runat="server"/> <input type="submit" OnServerClick="Submit_Click" Value="Submit" runat="server"/>

</form>

</body></html>

45