Professional Documents
Culture Documents
Tap Bai Giang LTUDWeb
Tap Bai Giang LTUDWeb
MC LC
- Vo menu File->New->Website
1.2.1.2. M ngun x l
- Phng thc Page_Load c gi mi khi trang .aspx c ti (load).
- Giao din m ngun ch Code C#:
10
Trong Templates, chn Web Form, sau o nhp tn trang web vo Name v click vo
OK.
Lu :
11
Ghi ch:
Trong biu thc logic ca cu trc if trn
!IsPostBack tng ng vi IsPostBack == false
12
Din gii
Nhn dng iu khin
Ni dung hin thi
Cho php hin th hay khng (true/false)
Trang aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "xin cho";
}
Din gii
SingleLine(mc
nh),
Multiline
(rows,columns), Password.
T ng PostBack ln Server khi Textbox co
thay i, mc nh l False
None / Disabled / Company /
Din gii
13
GroupName
Trang aspx:
<asp:RadioButton
Text="N" />
<asp:RadioButton
Text="Nam" />
runat="server"
GroupName="Phai"
ID="RadioButton2"
runat="server"
GroupName="Phai"
Din gii
ng dn hnh nh lm nhn lin kt
ng dn lin kt
Trang aspx:
<asp:Calendar ID="Calendar1" runat="server"
OnSelectionChanged="Calendar1_SelectionChanged"> </asp:Calendar>
Trang aspx.cs:
protected void Calendar1_SelectionChanged(object sender,
EventArgs e)
{
Label1.Text = Calendar1.SelectedDate.ToString();
}
* Trang aspx
<asp:Label ID="Label1" runat="server">S thch:</asp:Label><br />
<asp:CheckBox ID="SoThich1" runat="server" Text="Th thao" />
<asp:CheckBox ID="SoThich2" runat="server" Text="Nghe nhc" />
<asp:CheckBox ID="SoThich3" runat="server" Text="Xem phim" />
<br />
<br />
<asp:Button ID="btn_Chon" runat="server" Text="Chn"
OnClick="btn_Chon_Click" />
<br />
<div id="txt_HienThi" runat="server"/>
* Trang aspx.cs
protected void btn_Chon_Click(object sender, EventArgs e)
{
string s;
s = "";
if (SoThich1.Checked == true)
s = s + SoThich1.Text + " ";
if (SoThich2.Checked == true)
s = s + SoThich2.Text + " ";
if (SoThich3.Checked == true)
s = s + SoThich3.Text;
//Xut kt qu
txt_HienThi.InnerText = s;
}
15
Trang aspx
<asp:Image ID="Image1" runat="server"
ImageUrl="~/BaiGiang3/Hinh/Garden.jpg" Height="228px" Width="306px" />
Din gii
AutoPostBack
DataSource
DataTextField
DataValueField
SelectedIndex
SelectedItem
SelectedValue
Items
16
Trang aspx.cs:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = RadioButtonList1.SelectedValue;
}
Trang aspx.cs:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string[] C = new string[4] {"CTH", "CCK","CT","CVT"};
string[] T = new string[3] {"TCTH","TCCK","TCKT"};
if (DropDownList1.SelectedValue == "0") {
DropDownList2.DataSource = C; }
else
DropDownList2.DataSource = T;
DropDownList2.DataBind();
DropDownList2.Visible = true;
}
17
Trang aspx
<asp:CheckBoxList ID="cbl_SoThich" runat="server"
RepeatDirection="Horizontal">
<asp:ListItem Value="0">Th thao</asp:ListItem>
<asp:ListItem Value="1">Nghe nhc</asp:ListItem>
<asp:ListItem Value="2">Xem phim</asp:ListItem>
</asp:CheckBoxList><br />
<asp:Button ID="btn_Chon" runat="server" Text="Chn"
OnClick="btn_Chon_Click"/>
<br />
<br />
<div id="txt_HienThi" runat="server"/>
Trang aspx.cs
protected void btn_Chon_Click(object sender, EventArgs e)
{
string s;
s = "";
foreach (ListItem list in cbl_SoThich.Items)
{
if (list.Selected == true)
s = s + list.Text;
}
txt_HienThi.InnerText = "S thch:" + s;
}
Din gii
18
SelectionMode
Trang aspx:
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
Trang aspx.cs:
for (int i = 1; i <= 12; i++)
{
ListBox1.Items.Add(i.ToString());
}
Trang aspx:
S thch:
<asp:ListBox ID="ListBox1" runat="server" Rows="6"
SelectionMode="Multiple">
<asp:ListItem>Xem phim</asp:ListItem>
<asp:ListItem>Th thao</asp:ListItem>
<asp:ListItem>Du lch</asp:ListItem>
<asp:ListItem>Nghe nhc</asp:ListItem>
<asp:ListItem>Khác</asp:ListItem>
</asp:ListBox>
Trang aspx.cs:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Bn chn:";
foreach (ListItem li in ListBox1.Items)
{
if (li.Selected == true)
Label1.Text += li.Text + " ";
}
}
Text="Lu" />
Trang aspx.cs:
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
FileUpload1.SaveAs(Server.MapPath("hinh")+"\\" +FileUpload1.FileName);
}
Kch thc tp tin upload gii hn l: 4MB (4096KB). Co th thay i gii hn ny nh sau:
Trong tp tin Web.config thm trong th <system.web>
19
<httpRuntime
executionTimeout="90"
maxRequestLength="4096"
/>
2.6.1. RequiredFieldValidator
Kim tra iu khin khng c rng.
Trang aspx:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ControlToValidate="txtTen" ErrorMessage="cha nhp">
</asp:RequiredFieldValidator>
2.6.2. RangeValidator
Kim tra iu khin phi l chui, s, ngy, . Nu rng th khng kim tra.
Thuc tnh: MaximumValue, MinimumValue, Type (String, Interger, Date, ),
Trang aspx:
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="T 1 n 10 triu"
MaximumValue="10000000" MinimumValue="1" > </asp:RangeValidator>
2.6.3. CompareValidator
So snh iu khin ny vi iu khin khc hay mt gi tr c th. Nu rng th khng
kim tra.
Thuc tnh: ControlToCompare, Operator(Equal, GreaterThan, LessThan, ), Type,
ValueToCompare,
Trang aspx:
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToCompare="txtMatKhau" ControlToValidate="txtMatKhauLai"
ErrorMessage="khng ging " Display="Dynamic">
</asp:CompareValidator>
20
2.6.4. RegularExpressionValidator
Kim tra gi tr trong iu khin phi ph hp vi gi tr cho trc. Nu rng th
khng kim tra.
Thuc tnh: ValidationExpression,
Trang aspx:
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server" ControlToValidate="txtEmail" ErrorMessage="khng hp
l"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([.]\w+)*">
</asp:RegularExpressionValidator>
2.6.5. CustomValidator
Thc hin kim tra do ngi dng t nh ngha.
Thuc tnh: ClientValidationFunction, OnServerValidation
2.6.6. ValidationSummary
Tp hp cc thng bo li.
Thuc tnh: DisplayMode, ShowMessageBox, ShowSummary,
21
23
24
Mt s style:
Font
Background
Text
Position
Layout
Edges
List
Others
3.1.3.2. Dng Style cho ContentPlaceHolder
Click phi chut vo vng trng nm ngoi khung ContentPlaceHolder, chn Style
25
1. Click phi chut vo tn Website trn Solution Explorer v chn Add New Item.
2. Trong hp thoi Add New Item, chn Web Form.
3. Trong Name, nhp trn trang Web.
4. Chn vo checkbox Select Master Page.
5. Click vo nt Add.
6. Trong hp thoi Select a Master page, chn trang Master Page.
7. Click OK.
26
Cu hi:
1. B sung trang Master Page cho mt trang Web co sn
2. Vn chn hnh vo Master Page, Web Form
27
28
4.2. Response
HttpResponse c dng chuyn d liu t Server v Client
Gi tt c thng tin x l cho cc client, chng ta co th s dng i tng ny giao tip
vi ngi dng.
Phng thc
Write: xut thng tin dng chui ra trang web, khng th qui nh v tr xut.
Redirect: chuyn sang a ch khc.
WriteFile: ghi lung d liu ra tp tin.
Clear, end, flush
V d
Response.write (str)
Response.write (str)
Response.Redirect("abc.aspx")
4.3. Request
HttpRequest c dng chuyn d liu t Client v Server.
Nhn tt c gi tr m trnh duyt ca client gi n server thng qua mt yu cu HTTP
request.
29
V d 1
<asp:HyperLink ID="HyperLink1" runat="server">HyperLink</asp:HyperLink>
protected void Page_Load(object sender, EventArgs e)
{
HyperLink1.NavigateUrl = "a.aspx?x=111&y=222";
}
V d 2
Response.Write(Request.Browser.Browser + "<br>");
Response.Write(Request.Browser.Version + "<br>");
Response.Write(Request.Browser.Platform + "<br>");
Response.Write(Request.Browser.JavaScript + "<br>");
4.4. Application
Application c dng qun l tt c cc thng tin ca 1 website. Mt bin nu c
khai bo trong 1 trang web, no s b hy ngay khi Server x l xong trang ny. co th khai
bo cc bin s dng cho nhiu trang hay nhiu ln x l trang co th s dng i tng
Application. D liu lu trong Application s c chia s cho tan b ng dng, tan
b ngi dng v co th tn ti trong c chu trnh sng ca website.
4.5. Session
Session c dng lu tr cc thng tin dng cho mt phin lm vic ca mt ngi
30
n Web server sau khong thi gian timeout. D liu lu trong Session s c chia s cho
tan b ng dng ca 1 ngi dng.
Thuc tnh TimeOut: t thi gian ht hn (tnh bng pht, mc nh l 20).
Phng thc Abandon: hy Session hin hnh ngay lp tc.
Tp tin global.asax:
Tp tin ny c dng khi cn khai bo v vit cc x l cho cc s kin ca bin
Application, Session.
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
}
</script>
4.6. Cookies
Cookies l i tng m Server dng lu thng tin ngi dng ngay ti my Client di dng tp
tin.
V d
if (Request.Browser.Cookies == true)
{
if (Request.Cookies["LastVisit"] == null)
{
HttpCookie cookie = new HttpCookie("LastVisit",
DateTime.Now.ToString());
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
Label2 .Text = "y l ln u tin bn truy cp website ny";
}
else
31
{
HttpCookie cookie = Request.Cookies["LastVisit"];
Label2.Text = "Ln cui bn truy cp l" + cookie.Value;
Response.Cookies["LastVisit"].Value = DateTime.Now.ToString();
Response.Cookies["LastVisit"].Expires = DateTime.Now.AddDays(1);
}
}
else
{
Label2.Text = "Trnh duyt khng h tr cookie";
}
4.7. Server
i tng Server thuc lp HttpServerUtility cung cp cc phng thc dng cho vic
x l cc yu cu t pha Server.
* Cc thuc tnh
STT
Tn thuc tnh
M t
V d
Tr v tn ca my
tnh server
Ly tn ca my tnh server:
string sComputerName;
MachineName
sComputerName = Server.MachineName;
2
ScriptTimeout
Gn hoc tr v thi
gian ti a nhn yu
cu (request) t
client (tnh bng
giy)
Tn phng
thc
M t
V d
Tr v ng dn vt l ca Ly ng dn vt l ca th mc o
th mc o (virtual directory) MyWebSite trn my ch web:
trn my ch web
String FilePath;
MapPath
FilePath =
Server.MapPath("/MyWebSite");
32
M ho chui a ch URL
dng cho vic truyn t my
ch Web n client thng qua
giao thc HTTP.
UrlEncode
String MyURL;
MyURL =
"http://www.abc.com/articles.a
spx?title = ASP.NET Examples";
Response.Write( "<A HREF = " +
Server.UrlEncode(MyURL) + ">
ASP.NET Examples <br>" );
Gii m chui c m
ho t giao thc HTTP v
gi cho server bng a
ch URL.
UrlDecode
String DecodedString =
Server.UrlDecode(EncodedString
);
Transfer
33
4.8. Exception
- Exception l lp i tng dng by li trong sut qu trnh thc thi ng dng
(Windows, Web).
- Khi mt li xut hin trong khi thc thi ng dng, th h thng cng nh ng dng
ang thc thi s thng bo thng tin v li thng qua Exception.
- Exception thng kt hp vi lnh trycatch
- Thuc tnh quan trng:
+ Message: Cho bit m t thng tin v li.
V d: Xy dng trang web tnh bnh phng ca 1 s nguyn.
Trang .aspx:
<asp:Label ID="Label1" runat="server" Text="n:"></asp:Label>
<asp:TextBox ID="txt_n" runat="server"></asp:TextBox><br />
<asp:Button ID="btn_TinhBinhPhuong" runat="server" Text="Bnh phng"
OnClick="btn_TinhBinhPhuong_Click" /><br />
<br />
<asp:Label ID="lb_KetQua" runat="server"></asp:Label></div>
Trang .aspx.cs
protected void btn_TinhBinhPhuong_Click(object sender, EventArgs e)
{
string s;
int n;
int kq;
try
{
s = txt_n.Text;
//chuyn t chui sang s nguyn
n = int.Parse(s);
//bnh phng
kq = n * n;
34
//xut kt qu
lb_KetQua.Text = kq.ToString();
}
catch (Exception ex)
{
//Nu xy ra li th xut thng bo li
lb_KetQua.Text = ex.Message;
}
}
35
5.2.1. Connection
Thit lp kt ni gia ng dng vi ngun d liu
V d 1
string ChuoiKetNoi;
ChuoiKetNoi = "provider=microsoft.jet.oledb.4.0;Data Source=" + _
Server.MapPath("App_Data\\db1.mdb");
OleDbConnection c =new OleDbConnection (ChuoiKetNoi);
c.Open ();
V d 2
string ChuoiKetNoi;
ChuoiKetNoi = "server=localhost;UID=;PWD=;database=Sach;Integrated
Security=True;";
SqlConnection c =new SqlConnection (ChuoiKetNoi );
c.Open ();
5.2.2. Command
Thc thi cc cu lnh SQL hay Stored Procedure
36
V d
string ChuoiKetNoi;
ChuoiKetNoi = "provider=microsoft.jet.oledb.4.0;Data Source=" + _
Server.MapPath("App_Data\\db1.mdb");
OleDbConnection c =new OleDbConnection (ChuoiKetNoi );
c.Open ();
string ChuoiTruyVan;
ChuoiTruyVan = "select count(*) from ThanhVien";
OleDbCommand m = new OleDbCommand();
m.Connection = c;
m.CommandText = ChuoiTruyVan;
int n;
n = (int)m.ExecuteScalar();
Response.Write("s dng d liu:" + n);
5.2.3. DataReader
L lp ch c v d liu c theo mt chiu. Tit kim b nh v ti mt thi im ch lu tr mt
mu tin. Phng thc Read dng c mu tin, no t ng chuyn n mu tin k tip cho n khi
khng cn mu tin no, khng co khi nim nh hng EOF/BOF/Next/Previos
Thng c dng hin th d liu ra mn hnh 1 ln, kim tra d liu co tn ti hay khng.
V d 1
string ChuoiKetNoi;
ChuoiKetNoi = "provider=microsoft.jet.oledb.4.0;Data Source=" +
Server.MapPath("App_Data\\db1.mdb");
OleDbConnection c =new OleDbConnection (ChuoiKetNoi );
c.Open ();
string ChuoiTruyVan;
ChuoiTruyVan="select * from ThanhVien";
OleDbCommand m=new OleDbCommand();
m.Connection =c;
m.CommandText =ChuoiTruyVan ;
OleDbDataReader d;
d=m.ExecuteReader();
while (d.Read())
{
Response.Write("<br>Tn: ");
Response.Write(d["Ten"].ToString ());
}
d.Close();
V d 2
37
string ChuoiKetNoi;
ChuoiKetNoi = "server=localhost;UID=;PWD=;database=Sach;Integrated
Security=True;";
SqlConnection c =new SqlConnection (ChuoiKetNoi );
c.Open ();
string ChuoiTruyVan;
ChuoiTruyVan="select * from NhaXuatBan";
SqlCommand m=new SqlCommand();
m.Connection =c;
m.CommandText =ChuoiTruyVan ;
SqlDataReader d;
d=m.ExecuteReader();
while (d.Read())
{
Response.Write("<br>Tn: ");
Response.Write(d["TenNXB"].ToString ());
}
d.Close();
V d 1 truy xut d liu Access, v d 2 truy xut d liu SQLServer, so snh s khc nhau?
5.2.4. DataAdapter
Kt ni ngun d liu v in d liu vo b nh thng tr DataSet.
Thuc tnh: SelectCommand, InsertCommand, UpdateCommand, DeleteCommand tng ng cc
pht biu SQL dng thao tc d liu trn DataSet.
Phng thc Fill: thc thi SelectCommand v in d liu vo i tng DataSet.
Phng thc Update: gi i tng Command thc thi InsertCommand, UpdateCommand,
DeleteCommand.
5.2.5. DataSet
DataSet c xem nh nh ca mt ngun d liu thu nh co kh nng hot ng c lp khi ngt
kt ni. DataSet co th cha cc bng (DataTable), view (DataView), quan h (Relations), rng
buc (Contraints) nh mt Database tht s.
5.2.6. DataTable
5.2.7. DataView
5.3. Kt ni d liu trong ASP.NET
5.3.1. Thm
38
5.3.2. Xo
c.Open();
string ChuoiTruyVan;
ChuoiTruyVan = "select * from ThanhVien";
OleDbCommand m = new OleDbCommand();
m.Connection = c;
m.CommandText = ChuoiTruyVan;
OleDbDataAdapter a = new OleDbDataAdapter();
a.SelectCommand = m;
DataSet d = new DataSet();
a.Fill(d);
DropDownList1.DataTextField = "Ten";
DropDownList1.DataValueField = "Ten";
DropDownList1.DataSource = d;
DropDownList1.DataBind();
c.Close();
}
}
protected void Xoa_Click(object sender, EventArgs e)
{
string t=DropDownList1.SelectedValue;
string ChuoiKetNoi;
ChuoiKetNoi = "provider=microsoft.jet.oledb.4.0;Data Source=" +
Server.MapPath("App_Data\\db1.mdb");
OleDbConnection c = new OleDbConnection(ChuoiKetNoi);
c.Open();
string ChuoiTruyVan;
ChuoiTruyVan = "delete * from ThanhVien where Ten=a1";
OleDbCommand m = new OleDbCommand();
m.Connection = c;
m.Parameters.Add("a1", t);
m.CommandText = ChuoiTruyVan;
try
{
m.ExecuteNonQuery();
c.Close();
Response.Redirect("KetNoiDuLieuAccess.aspx");
}
catch (Exception ex)
{
Response.Write("THNG BO LI" + ex.Message);
}
c.Close();
}
40
42
6.2. GridView
Cho php hin th d liu dng bng, kt qu xut ra trnh duyt l th <table>. Co th: phn trang;
sp xp tng ct d liu; chn, xoa, cp nht tng dng d liu.
To 1 GridView: Toolbox->nhp i chut vo GridView
To ngun d liu cho GridView
Bc 1: nhp chut
Bc 2: chn
43
44
Sp xp d liu theo ct
Gn thuc tnh ca GridView: AllowSorting=True
Gn thuc tnh ca cc ct mun sp xp: SortExpression=TnCt
Phn trang d liu
Gn thuc tnh ca GridView: AllowPaging=True, PageSize=s lng mu tin
trong 1 trang
phn
6.3. DataList
DataList control l iu khin dng hin th d liu trn Web, khi s dng DataList control
chng ta phi t thit k cch thc hin th d liu.
V d:
45
46
Bc 1: nhp chut
Bc 2: chn
47
48
Bc 1: nhp chut
49
Bc 2: chn
Bc 1: nhp chut
50
Bc 2: chn
51
Kt qu:
52
53
DSBaiHat.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DSBaiHat.aspx.cs"
Inherits="DSBaiHat" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="dlBaiHat" runat="server" GridLines="Both">
<HeaderTemplate>
<td>M Bi Ht</td>
<td>Tn Bi Ht</td>
<td>Tn Nhc S Sng Tc</td>
</HeaderTemplate>
<ItemTemplate>
<td><%#DataBinder.Eval(Container.DataItem,"MaBaiHat") %></td>
<td><a href='<%#"CTBaiHat.aspx?MaBaiHat="+
DataBinder.Eval(Container.DataItem,"MaBaiHat")
%>'>
<%#DataBinder.Eval(Container.DataItem,"TenBaiHat")
%></a></td>
<td><%#DataBinder.Eval(Container.DataItem,"TenNhacSi") %></td>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
Ghi ch:
- Biu thc databinding <%# biu_thc %> c dng b sung thm on m ngun
trong trang web ca ngn ng nh VB.NET, C#.
- DataBinder.Eval (Object, String): dng nh gi (evalutate) li biu thc
databinding vi mt i tng (Object) ti thi im runtime
- Container.DataItem: l nh danh ti thi im runtime cho DataItem.
DSBaiHat.aspx.cs
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;
using System.Data.OleDb;
using System.Data;
public partial class DSBaiHat : System.Web.UI.Page
54
{
public DataSet LayDanhSachBaiHat()
{
DataSet ds;
ds = new DataSet();
string sConnectString;
string sSql;
sConnectString = "Provider=Microsoft.Jet.OleDB.4.0;Data Source=" +
Server.MapPath("DB/MusicDB.mdb");
OleDbConnection myConn = new OleDbConnection(sConnectString);
sSql = "SELECT
MaBaiHat,TenBaiHat,NoiDung,TenNhacSi,BaiHat.MaNhacSi as MaNS FROM
BaiHat,NhacSi WHERE BaiHat.MaNhacSi=NhacSi.MaNhacSi";
try
{
myConn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(sSql, myConn);
da.Fill(ds);
myConn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
return ds;
}
public void HienThiDanhSachBaiHat()
{
try
{
DataSet ds;
ds = new DataSet();
ds = LayDanhSachBaiHat();
dlBaiHat.DataSource = ds.Tables[0];
dlBaiHat.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void Page_Load(object sender, EventArgs e)
{
HienThiDanhSachBaiHat();
}
}
<%#DataBinder.Eval(Container.DataItem,"TenNhacSi") %></a>
</td>
</ItemTemplate>
</asp:DataList><br />
</div>
</form>
</body>
</html>
CTBaiHat.aspx.cs
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Data;
System.Configuration;
System.Collections;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Web.UI.HtmlControls;
System.Data;
System.Data.OleDb;
return ds;
}
public void HienThiChiTietBaiHat(string sMaBaiHat)
{
try
{
DataSet ds;
ds = new DataSet();
ds = LayThongTinBaiHat(sMaBaiHat);
dlBaiHat.DataSource = ds.Tables[0];
dlBaiHat.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void Page_Load(object sender, EventArgs e)
{
string sMaBaiHat;
if (Request.QueryString["MaBaiHat"] != null)
{
sMaBaiHat = Request.QueryString["MaBaiHat"];
HienThiChiTietBaiHat(sMaBaiHat);
}
}
}
6.5. DetailView
DetailsView l iu khin cho php hin th mt mu tin hoc mt i tng ti mt im.
V d:
58
59
Bc 1: nhp chut
60
Bc 2: chn
61
Bc 2: chn
Kt qu:
62
63
Chng 7: Khc
7.1. IIS
64
65
6) Ci t xong!
66
67
Th li kt qu trang HTML.
68
Th li kt qu trang ASP.
69
70
2.1) y l nhng thuc tnh khi qut ca Web site. y chung ta co th gn IP, vo cng
c nh cho web site bng cch vit vo IP v port. Mc nh ban u IP s co IP gn c ho
my v cng 80. Ngoi ra ta co th mc nh thi gian server dnh ra cho tng mi kt ni t
client trc khi ngt kt ni o.
2.2) Phn hiu sut co nhng c tnh sau, v tuy theo mt truy cp web site thay hiu
xut ca web site v cc ti nguyn ca my dnh cho web service, nh tng thm thi gian
s dng CPU cho web service khi nhiu ngi truy cp.
71
2.4) Phn document l xc nh mt danh sch cc trang default khi goi url ca web site.
72
73
Bai1_XuatTBChao.htm
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script language="javascript">
var sTen = new String();
sTen = prompt("Vui lng nhp tn: ");
alert ("Xin cho bn " + sTen);
</script>
</head>
<body>
</body>
</html>
Bai2a_TinhTong2SoNguyen.htm
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script language="javascript">
75
76
Bai2b_TinhTong2SoNguyen.htm
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script language="javascript">
function TinhTong()
{
var a, b = new Number();
var S = new Number();
var Chuoi = new String();
Chuoi = document.getElementById("txt_a").value;
a = parseInt(Chuoi);
Chuoi = document.getElementById("txt_b").value;
b = parseInt(Chuoi);
S = a + b;
//Xut kt qu
var newChild;
var oldChild;
Chuoi = "Tng: " + S;
newChild = document.createTextNode(Chuoi);
oldChild=document.getElementById("KetQua").childNodes[0];
document.getElementById("KetQua").replaceChild(newChild,oldChild);
}
</script>
</head>
<body>
<h1>Tng 2 s nguyn</h1>
a: <input id="txt_a" type="text" /> <br />
b: <input id="txt_b" type="text" /> <br />
<input id="Button1" type="button" value="Tnh tng"
onclick="TinhTong()"/>
<div id="KetQua"> </div>
</body>
</html>
77
Kt qu
78
Bai3_TinhCanhHuyenTGVuong.htm
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
</head>
<body>
<script language="javascript">
var a, b = new Number();
var c = new Number();
var Chuoi = new String();
Chuoi = prompt("Nhp cnh a: ");
a = parseInt(Chuoi);
Chuoi = prompt ("Nhp cnh b: ");
b = parseInt (Chuoi);
c = Math.sqrt(a*a+b*b);
alert ("Cnh huyn: " + c);
</script>
</body>
</html>
79
80
Bai4_TinhTongDaySoNguyen.htm
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script language="javascript">
var a = new Array();
var n = new Number();
var S = new Number();
var Chuoi = new String();
//Nhp
Chuoi = prompt("Nhp dy cc s nguyn: ");
a = Chuoi.split(",");
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
n = 4;
n = a.length;
for (var i=0; i < n; i++)
a[i] = parseInt(a[i]);
S = 0;
for (var i=0; i < n; i++)
S = S + a[i];
//Xut kt qu
alert ("Tng: " + S);
</script>
</head>
<body>
</body>
</html>
81
Bai5_Tong2PhanSo.htm
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script language="javascript">
function PhanSo()
{
this.TuSo = new Number();
this.MauSo = new Number();
}
82
function NhapPhanSo(A,B)
{
var Chuoi = new String();
//Phn s A
Chuoi = document.getElementById("txt_TuSoA").value;
A.TuSo = parseInt(Chuoi);
Chuoi = document.getElementById("txt_MauSoA").value;
A.MauSo = parseInt(Chuoi);
//Phn s B
Chuoi = document.getElementById("txt_TuSoB").value;
B.TuSo = parseInt(Chuoi);
Chuoi = document.getElementById("txt_MauSoB").value;
B.MauSo = parseInt(Chuoi);
}
function TinhTong(A,B)
{
var Kq = new PhanSo();
Kq.TuSo = A.TuSo * B.MauSo + B.TuSo * A.MauSo;
Kq.MauSo = A.MauSo * B.MauSo;
return Kq;
}
function XuatPhanSo(A)
{
var Chuoi;
Chuoi = A.TuSo + "/" + A.MauSo;
alert(Chuoi);
}
function XuLy ()
{
var A = new PhanSo();
var B = new PhanSo();
var S = new PhanSo();
NhapPhanSo(A,B);
S= TinhTong(A,B);
XuatPhanSo(S);
}
</script>
</head>
<body>
<h1>Tng 2 Phn S</h1>
Phn s A: T s: <input id="txt_TuSoA" type="text" /> Mu s: <input
id="txt_MauSoA" type="text" /> <br />
Phn s B: T s: <input id="txt_TuSoB" type="text" /> Mu s: <input
id="txt_MauSoB" type="text" /> <br />
<input id="Button1" type="button" value="Tnh tng" onclick="XuLy()"/>
</body>
</html>
83
7.3. AJAX
Mt s c im:
* X l h khch (Client):
+ u im:
- Giao din p
- Kh nng tng tc cao
- Gim ti cho Server
- Tc x l nhanh
+ Hn ch:
- Kho pht trin
- i hi phn mm h tr
- Kh nng tng thch vi trnh duyt khng cao.
* X l h phc v (Server)
84
+ u im:
- Pht trin n gin
- Trin khai v bo tr d dng
- Chia s c d liu
+ Khuyt im
- Giao din ngi dng th s
- Tnh tng tc km
85
86
Nu s dng trnh duyt Web IE7 tr ln, Firefox, Chrome, Opera, Safari
var xmlhttp = new XMLHTTPRequest();
M t
onreadystatechange
readyState
responseText
responseXML
87
status
statusText
Phng thc
M t
abort()
Dng gi yu cu n server
getAllResponseHeaders()
getresponseHeader(x)
open('method','URL','a')
send(content)
setRequestHeader('x','y')
ASP.NET
using
using
using
using
using
using
using
using
using
using
System;
System.Data;
System.Configuration;
System.Collections;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Web.UI.HtmlControls;
PHP
<?php
header('Content-Type: text/xml');
echo "<?xml version='1.0' encoding='UTF-8'?><Goc ThongBao='Xin cho n
vi AJAX'/>";
?>
7.3.3. V d
V d 1: Nhp vo tn ngi s dng. Xut thng bo cho
M ngun:
* X l h khch:
Bai1_XuatTBChao.htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script language="javascript">
var xmlhttp
function XuatThongBao()
{
var sTen = new String();
sTen = document.getElementById("txt_Ten").value;
89
* X l h phc v:
90
XuatThongBaoChao.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="XuatThongBaoChao.aspx.cs" Inherits="clsXuatThongBaoChao" %>
XuatThongBaoChao.aspx.cs
using
using
using
using
using
using
using
using
using
using
System;
System.Data;
System.Configuration;
System.Collections;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Web.UI.HtmlControls;
XML
= "<?xml version='1.0' encoding='UTF-8'?>";
+ "<Goc ";
+ "ThongBao='" + sThongBao + "'";
+ "/>";
Response.ContentType = "text/xml";
Response.Write(sXML);
}
}
91
M ngun:
* X l h khch:
Bai2_TinhTong2SoNguyen.htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script language="javascript">
var xmlhttp
function
{
var
var
var
TinhTong()
a, b = new Number();
S = new Number();
Chuoi = new String();
Chuoi = document.getElementById("txt_a").value;
a = parseInt(Chuoi);
Chuoi = document.getElementById("txt_b").value;
b = parseInt(Chuoi);
//gui ket qua ve server
var ThamSo = "a=" + a + "&b=" + b;
var URL = "./TinhTong2SoNguyen.aspx" + "?" + ThamSo;
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",URL,true);
xmlhttp.send(null);
92
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
var xmlDoc=xmlhttp.responseXML.documentElement;
S = xmlDoc.getAttribute("Tong");
Chuoi = "Tng: " + S;
var newChild = document.createTextNode(Chuoi);
var oldChild =
document.getElementById("KetQua").childNodes[0];
document.getElementById("KetQua").replaceChild(newChild,
oldChild);
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// dng cho IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// dng cho IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
</head>
<body>
<h1>Tng 2 s nguyn</h1>
a: <input id="txt_a" type="text" /> <br />
b: <input id="txt_b" type="text" /> <br />
<input id="Button1" type="button" value="Tnh tng"
onclick="TinhTong()"/>
<div id="KetQua"> </div>
</body>
</html>
93
* X l h phc v
TinhTong2SoNguyen.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="TinhTong2SoNguyen.aspx.cs" Inherits="clsTinhTong2SoNguyen" %>
TinhTong2SoNguyen.aspx.cs
using
using
using
using
using
using
using
using
using
using
System;
System.Data;
System.Configuration;
System.Collections;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Web.UI.HtmlControls;
XML
= "<?xml version='1.0' encoding='UTF-8'?>";
+ "<Goc ";
+ "Tong='" + S.ToString() + "'";
+ "/>";
Response.ContentType = "text/xml";
Response.Write(sXML);
}
}
c m t bng XML. Web service cung cp cc phng thc chun trong vic gi v truy cp n
cc h thng ong goi v h thng k tha.
Cc phn mm c vit bi nhng ngn ng lp trnh khc nhau v chy trn nhng nn
tng khc nhau co th s dng dch v web (web service) chuyn i d liu thng qua mng
Internet theo cch giao tip tng t bn trong mt my tnh. No bao gm cc module c lp cho
hot ng ca khch hng v doanh nghip v bn thn no c thc thi trn server.
Web service gip gim chi ph v phc tp trong tch hp v pht trin h thng.
7.4.2. c im
Web service cho php client v server tng tc c vi nhau ngay c tro ng nhng mi
trng khc nhau.
V d: t Web server cho ng dng trn mt my ch chy h iu hnh Linux trong khi
ngi dng s dng my tnh chy h iu hnh Windows, ng dng vn co th chy v x l bnh
thng m khng cn thm yu cu c bit tng thch gia hai h iu hnh ny.
Phn ln k thut ca web service c xy dng da trn m ngun m v c pht trin t
cc chun c cng nhn chng hn nh XML.
Mt web service bao gm co nhiu module v co th cng b ln mng Internet.
96
97
98
99
100
Nhp a ch URL ca Web Service, sau o nhp tn vo Web reference name v click vo Add
Reference
101
Xy dng m ngun:
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;
namespace test_WS
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_XuatTBChao_Click(object sender, EventArgs e)
{
MyWebService.Service ws = new MyWebService.Service();
string sThongBao;
sThongBao = ws.XuatThongBaoChao();
MessageBox.Show(sThongBao);
}
private void btn_TinhTong_Click(object sender, EventArgs e)
{
MyWebService.Service ws = new MyWebService.Service();
int a = int.Parse(txt_a.Text);
int b = int.Parse(txt_b.Text);
int s = ws.TinhTong(a, b);
MessageBox.Show(s.ToString());
}
}
}
Kt qu thc hin:
102
* HTML page
103
M ngun: test_WS.htm
<html >
<head>
<title>Vi du web service</title>
<script language="JavaScript">
function InitializeService()
{
service.useService("http://localhost:61076/ViDu_WebService/Service.asmx?ws
dl","Service");
}
function Check()
{
var a = document.getElementById("txt_a").value;
var b = document.getElementById("txt_b").value;
service.Service.callService("TinhTong", a, b);
}
function ShowResult()
{
var kq;
kq = event.result.value;
alert(kq);
}
</script>
</head>
<body onload="InitializeService()" >
104
105