bài 3: server control

54
Bài 3: SERVER CONTROL 3.1. Html Server control 3.2. Web Server control 3.3. Client-Side Callback

Upload: becca

Post on 15-Jan-2016

41 views

Category:

Documents


2 download

DESCRIPTION

Bài 3: SERVER CONTROL. 3.1. Html Server control 3.2 . Web Server control 3.3. Client-Side Callback. 3.1 HTML Server Control. Khái niệm Cách tạo Thứ bậc Các sự kiện Xử lý dữ liệu. Khái niệm. HTML control là các đoạn mã dùng tạo các điều khiển trên giao diện - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Bài 3: SERVER CONTROL

Bài 3:SERVER CONTROL

3.1. Html Server control 3.2. Web Server control 3.3. Client-Side Callback

Page 2: Bài 3: SERVER CONTROL

3.1 HTML Server Control

• Khái niệm• Cách tạo• Thứ bậc• Các sự kiện• Xử lý dữ liệu

Page 3: Bài 3: SERVER CONTROL

Khái niệm

• HTML control là các đoạn mã dùng tạo các điều khiển trên giao diện

• HTML control thường chỉ được sử lý ngay tại Web Browser (<h>, <a>, <input> …)

• Các HTML control có thể được xử lý ngay tại phía server bằng cách chuyển chúng thành các HTML server control

Page 4: Bài 3: SERVER CONTROL

Ví dụ

<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Các điều khiển giao diện</title> <script type="text/javascript"> function Tinh() { var x, y; x = parseInt(document.getElementById("txtA").value); y = parseInt(document.getElementById("txtB").value); document.getElementById("txtTong").value = x + y; } </script> </head><body> <form id="form_chinh" > Nhập số A:<input type="text" id="txtA" /> <br /> Nhập số B:<input type="text" id="txtB" /> <br /> <input type="button" onclick="Tinh();" name="btnTinh" value="Tổng" /><br /> Tổng là:<input type="text" id="txtTong" /><br /></form></body></html>

Page 5: Bài 3: SERVER CONTROL

Cách tạo

• Cú pháp:<TagName runat=“server”></TagName>

• Ví dụ:<input type=“text” name=“txtA” runat=“server”/>

• Tất cả HTML Server Control phải được đặt trong tag <form> với thuộc tính runat = “server”

<form id="form1" runat="server">……</form>

Page 6: Bài 3: SERVER CONTROL

• Hệ thống thứ bậc của HTML Server Controls System.Object

System.Web.UI.Control

HtmlControl

HtmlImage

HtmlInputControl

HtmlInputFile

HtmlInputHidden

HtmlInputImage

HtmlInputRadioButton

HtmlInputText

HtmlInputButton

HtmlInputCheckBox

HtmlContainerControl

HtmlForm

HtmlGenericControl

HtmlSelect

HtmlTable

HtmlTableCell

HtmlTableRow

HtmlTextArea

HtmlAnchor

HtmlButton

<table>

<form>

<input type=button>

<tr>

<td>,<th>

<input type=text>

<textarea>

<input type=image>

<input type=file>

<input type=hidden>

<input type=radio>

<input type=checkbox>

<select>

<a>

<span>,<div>, ...

<button>

<img>

Page 7: Bài 3: SERVER CONTROL

Các sự kiện

• Sự kiện: – onServerClick– onServerChange– onStartSelect,…

• Cú pháp:<tagName event=“Function_Process”></tagName>

Page 8: Bài 3: SERVER CONTROL

Xử lý dữ liệu từ HTML Server

• Cú pháp: controlfield_id.Value

• Ví dụ:<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Các điều khiển giao diện</title> <script runat="server"> public void btnsend_Serverclick(object sender, System.EventArgs e) { Response.Write("Hello " + txtA.Value); } </script></head><body> <form id="form2" runat="server"> Nhập ten:<input type="text" id="txtA" runat="server" /> <br /> <input type="submit" value="Send" id="btnsend" runat="server" onserverclick="btnsend_Serverclick" /> </form></body></html>

Page 9: Bài 3: SERVER CONTROL

Xử lý dữ liệu từ HTML Server

• Lưu ý: Đối với DIV, SPAN thì phải dùng thuộc tính .innerHTML để xử lý• Ví dụ:<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Các điều khiển giao diện</title> public void btnsend2_Serverclick(object sender, System.EventArgs e) { MySpan.InnerHtml="Xin chao " + txtB.Value; } </script></head><body> <form id="form2" runat="server"> Nhập ten 2:<input type="text" id="txtB" runat="server" /> <br /> <input type="submit" value="Send 2" id="btnsend2" runat="server" onserverclick="btnsend2_Serverclick" /> <br /> <b><span id="MySpan" runat="server"></span></b> </form></body></html>

Page 10: Bài 3: SERVER CONTROL

Thẻ Span & Div

• Thẻ <span> :– Là một thẻ trung hòa, nó không thêm hay bớt

bất cứ một thứ gì vào một tài liệu HTML cả– Dùng để nhóm một khối phần tử

• Thẻ <div> :– Cũng  là một thẻ trung hòa– Dùng để nhóm một hoặc nhiều khối phần tử

Page 11: Bài 3: SERVER CONTROL

Ví dụ

<body> <form id="form_chinh" > Không có gì quý hơn <span style="font-weight:bold">độc lập </span>tự do <ul> <div style="font-style:italic; color:Blue" > <li>Hà Nội</li> <li>Đà Nẳng</li> <li>TP Hồ Chí Minh</li> </div> <div style="background-color:Lime; width: 100px; height:auto; left:auto; top: auto;

color:Red"> <li>Quảng Nam</li> <li>Quảng Ngãi</li> <li>Bình Định</li> </div> </ul> </form></body>

Page 12: Bài 3: SERVER CONTROL

3.2 Web server control

• Khái niệm• Cách tạo• Thứ bậc• Các Control cơ bản• Các Control đặt biệt

Page 13: Bài 3: SERVER CONTROL

Khái niệm

• Web server control là những tag đặc biệt của ASP.NET

• Các control này được xử lý trên Server và đòi hỏi phải có thuộc tính runat= “server”

• Web server control tồn tại bên trong không gian tên System.Web.UI.WebControls

Page 14: Bài 3: SERVER CONTROL

Cách tạo

• Cú pháp:

<asp:ControlName id= “ControlID” runat=“sever” />

• Ví dụ:

<asp:Label ID=“lblMsg" runat="server"> </asp:Label>

Page 15: Bài 3: SERVER CONTROL

Hệ thống thứ bậc của Web Server Control

Syst em. Obj ect

Syst em. Web. UI . Cont r ol

WebCont r ol

AdRot at or

BaseDat aLi st

Dat aGr i d

Dat aLi st

But t on

Cal endar

CheckBox

Radi oBut t on

Hyper Li nk

I mage

I mageBut t on

Label

BaseVal i dat or

BaseCompar eVal i dat or

Cust omVal i dat or

RangeVal i dat or

Regul ar Expr essi onVal i dat or

Requi r edFi el dVal i dat or

Li nkBut t on

Li st Cont r ol

Radi oBut t onLi st

CheckBoxLi st

Dr opDownLi st

Li st Box

Panel

Tabl e

Tabl eCel l

Tabl eHeader Cel l

Tabl eRowText Box

Val i dat i onSummar y

Repeat er

Compar eVal i dat or

Xml

Page 16: Bài 3: SERVER CONTROL

Các Control cơ bản

• Label• Textbox• Button• CheckBox • Radio• Image• Hyperlink• List Controls group• Table• BulletedList

Page 17: Bài 3: SERVER CONTROL

Label

• Dùng hiển thị văn bản trên trình duyệt• Thuộc tính:

– ID: tên cho label – Khác: Tự nghiên cứu

• Ví dụ:

Page 18: Bài 3: SERVER CONTROL

TextBox

• Dùng để nhập liệu hoặc hiển thị văn bản chỉ đọc • Thuộc tính :

– AutoPostBack: có 2 giá trị True và False khi một hành động trên trang web bẩy một sự kiện

– TextMode: SingleLine, MultiLine, Pass– Value: Gán giá trị– ReadOnly: Dữ liệu không thay đổi– Khác: Tự nghiên cứu

• Sự kiện: Tự nghiên cứu

Page 19: Bài 3: SERVER CONTROL
Page 20: Bài 3: SERVER CONTROL

Button

• Thường sử dụng để submit form• Phân loại:

– Button– LinkButton– ImageButton

• Sự kiện– Onclick()– OnserverClick()

Page 21: Bài 3: SERVER CONTROL

Button

<asp:Button Text="Tính tổng" ID="btntinh" runat="server" onclick="btntinh_Click" /> <br /><asp:LinkButton Text="Click ở đây" ToolTip="Gọi phương thức tính tổng" onclick="btntinh_Click" runat="server"/> <br /><asp:ImageButton ImageUrl="~/hinh1.gif" onclick="btntinh_Click" runat="server" Height="74px" Width="82px" />

Page 22: Bài 3: SERVER CONTROL

CheckBox

• Các thuộc tính:o Type "checkbox" o Id tên checkboxo Text Nhãno Checked <tên id>.Checked = True/Falseo Item[n].Selected <tên id>.Item[n].Selected=True/Falseo SelectedItem <tên id>. SelectedItem o SelectedValue <tên id>. SelectedValueo SelectedIndex <tên id>. SelectedIndex

• Sự kiện:– Onclick()– Onserverclick ()

Page 23: Bài 3: SERVER CONTROL

CheckBox

<body> <form id="form1" runat="server"> <p>Bạn chọn màu</p> <p> <input type="checkbox" id="maudo" runat="server" />&nbsp; Đỏ<br /> <input type="checkbox" id="mauxanh" runat="server" />&nbsp; Xanh<br /> </p> <p> <input type="submit" id="btnSubmit" value="Submit " runat="server"

onserverclick="btnSubmit_Click" /> </p> </form> <div id="lbltext" runat ="server" > </div> </body>

<asp:CheckBox ID="CheckBox1" runat="server" Text="ghdf" />

<asp:CheckBoxList ID="chkchon" runat="server" > <asp:ListItem Text="Photo tài liệu - 2.000 đ" /> <asp:ListItem Text="Đĩa CD tài liệu - 7.000 đ" /></asp:CheckBoxList>

Page 24: Bài 3: SERVER CONTROL

protected void btnSubmit_Click(object sender, EventArgs e) { string maudachon = " "; if (maudo.Checked) { maudachon = "Đỏ "; } if (mauxanh.Checked) { maudachon = "Xanh "; } if ((maudo.Checked) && (mauxanh.Checked)) { maudachon = "Đỏ Xanh "; } if (Page.IsPostBack) { lbltext.InnerHtml = “Bạn chọn màu: " + maudachon; } }

Page 25: Bài 3: SERVER CONTROL

RadioButton• Thuộc tính:

o Type "RadioButton" o Id tên RadioButtono Text Nhãno Checked <tên id>.Checked = True/Falseo SelectedItem <tên id>. SelectedItem o SelectedValue <tên id>. SelectedValueo SelectedIndex <tên id>. SelectedIndex

• Sự kiện– onClick()– onCheckedChanged()

<asp:RadioButtonList ID="rabgt" runat="server"> <asp:ListItem Text="Nam" /> <asp:ListItem Text="Nữ" /></asp:RadioButtonList>

Page 26: Bài 3: SERVER CONTROL

image

• Type: Image• ImageUrl : Địa chỉ của hình cần hiển thị• AlternateText: Dòng văn bản hiển thị khi hình không có

sẳn• ImageAlign: Canh vị trí tương đối của hình so với văn

bản trên trang• Height: Chiều cao• Width: Chiều rộng• ToolTip: Thông báo khi rà mouse

Xem thêm ImageButtonPostBackUrl

Page 27: Bài 3: SERVER CONTROL

HyperLink

• ImageUrl: Đường dẫn đến hình cần hiển thị (nếu dùng thuộc tính này thì hyperlink có tác dụng giống như Imagebutton)

• NavigateUrl: Địa chỉ URL cần link đến• Text: Chuỗi văn bản chỉ mục liên kết hiển thị

trên trình duyệt• Target: Chỉ cửa sổ hiển thị trang đích

Page 28: Bài 3: SERVER CONTROL

ListControl

• DropDownList• ListBox• CheckBoxList• RadioButtonList

<asp:ListControlName Id=“IdName” runat=“Server”> <asp:ListItem Value=”value” Text=“text”></asp:ListItem></asp:ListControlName>

<asp:ListControlName Id=“IdName” runat=“Server”> <asp:ListItem Value=”value” Text=“text”></asp:ListItem></asp:ListControlName>

Page 29: Bài 3: SERVER CONTROL

ListControl

ListBox DropDownList CheckBoxList RadioButtonList<asp:ListBox ID="ListBox1" runat="server">

<asp:ListItem>Quảng Ngãi</asp:ListItem> <asp:ListItem>Đà Nẳng</asp:ListItem></asp:ListBox>

Item: có thể được tạo theo cách Coding hoặc Design

Items.Count: trả về số phần tử trong listControls

Items.Add(ListItem): thêm phần tử vào listControls

Items.Remove(ListItem): xoá phần tử khỏi ListControl

Items.Clear(): Xoá tất cả các phần tử.

Items[i].Selected: trả về true hoặc false.

Page 30: Bài 3: SERVER CONTROL

• SelectedIndex: trả về chỉ số của phần tử được chọn

• SelectedItem: trả về phần tử được chọn.• SelectedValue: trả về giá trị được chọn.• Sự kiện: SelectedIndexChaged

Thuộc tính và sự kiện

Page 31: Bài 3: SERVER CONTROL

Dữ liệu cho ListControl

• DataSource: thiết lập giá trị từ DataSource như DataTable,DataSet,Array,Collection,DataView

• DataTextField: thiết lập phần tử text từ DataSource

• DataValueField: thiết lập giá trị phần tử từ DataSource

• DataBind(): binding data vào ListControl

Page 32: Bài 3: SERVER CONTROL

Table • Table: Hiển thị thông tin dưới dạng dòng và cột. • Table control cho phép xây dựng các bảng động bằng mã lệnh

sử dụng các thuộc tính tập hợp Table Rows và Table Cells• Tạo Table : Disgin hoặc Code

ASP ControlHTML

HTMLControl

Table <table>

TableRow <tr>

TableHeaderCell <th>

TableCell <td>

Page 33: Bài 3: SERVER CONTROL

ASP ControlHTML

<asp:Table ID="Table1" runat="server" Height="223px" Width="411px" GridLines="Both"> <asp:TableRow Width="8px"> <asp:TableHeaderCell Width="12px">Cột 1</asp:TableHeaderCell> <asp:TableHeaderCell>Cột 2</asp:TableHeaderCell> <asp:TableHeaderCell>Cột 3</asp:TableHeaderCell> </asp:TableRow> <asp:TableRow ID="b" runat="server"> <asp:TableCell runat="server">c1</asp:TableCell> <asp:TableCell runat="server">c2</asp:TableCell> </asp:TableRow> <asp:TableRow ID="c" runat="server"> <asp:TableCell runat="server"></asp:TableCell> <asp:TableCell runat="server"></asp:TableCell> </asp:TableRow></asp:Table>

Page 34: Bài 3: SERVER CONTROL

HTMLControl<table id="Table2" style="width:41%;" > <tr> <th>cột 1</th> <th>Cột 2</th> <th>Cột 3</th> </tr> <tr> <td class="style3"> &nbsp;</td> <td class="style2"> &nbsp;</td> <td> &nbsp;</td> </tr> <tr> <td class="style3"> &nbsp;</td> <td class="style2"> &nbsp;</td> <td> &nbsp;</td> </tr></table>

Page 35: Bài 3: SERVER CONTROL

BulletedList

<asp:BulletedList runat="server"BulletStyle="Numbered"

DisplayMode="Text" > <asp:ListItem Text="Mở đầu" /> <asp:ListItem Text="Thân bài" /> <asp:ListItem Text="Kết luận" /></asp:BulletedList>

Page 36: Bài 3: SERVER CONTROL

Các Control đặt biệt

• Panel• FileUpload• Calendar• AdRotator• Validation• Wizard

Page 37: Bài 3: SERVER CONTROL

Panel

• Được dùng như ContainerControl đối với các control khác

• Thi hành nhiều chức năng: Kiểm soát các control chứa trong Panel Control

• Được dẫn xuất từ lớp Webcontrol

<asp:Panel ID="Panel1" runat="server" BackColor="#99FF66" BackImageUrl="~/hinh1.gif" BorderStyle="Groove" Height="339px" Width="620px">

</asp:Panel>

Page 38: Bài 3: SERVER CONTROL

FileUpload

• Dùng thực hiện upload file lên server • Các thuộc tính:

– FileName: Tên file được upload lên– Hasfile: True/False tồn tại file không– FileBytes: Mảng bytes chứa nội dung file upload– PostedFile.Filename: Đường dẫn đầy đủ của file

– PostedFile.ContentType: Loại File (.doc, .mdb, …)– PostedFile.ContentLength: Kích thước của File.

• Các phưong thức:– SaveAs: Lưu file upload vào 1 thư mục bất kỳ– MapPath(): Trả về đường dẫn ảo của web server– PathGetExtension(): Trả về pahàn mở rộng của file

Page 39: Bài 3: SERVER CONTROL

Ví dụ

lblfile.Text = FileUpload1.PostedFile.FileName.ToString();lbltype.Text = FileUpload1.PostedFile.ContentType.ToString();lblsize.Text = FileUpload1.PostedFile.ContentLength.ToString();string filename;filename = FileUpload1.PostedFile.FileName.ToString();FileUpload1.PostedFile.SaveAs(Server.MapPath("")+"\\bai2.3"+filename);

Nên viết Code Bihind

Page 40: Bài 3: SERVER CONTROL

Calendar

• Cú pháp:<asp:Calendar ID="calendar1" runat="server"

FirstDayOfWeek="Monday" SelectedDate="2011-09-26"

onselectionchanged="layngay"></asp:Calendar>

• Các thuộc tính:– DayNameFormat: Định dạng– FirstDayOfWeek: Quy định ngày đầu tuần– SelectedDate: Lấy về hoặc thiết đặt cho ngày lựa chọn– <id>.SelectedDate.<ToString() / ToShortDateString() /

ToLongDateString()>;– <id>.SelectedDate.<Day / Month / Year>.ToString();

Page 41: Bài 3: SERVER CONTROL
Page 42: Bài 3: SERVER CONTROL

AdRotator

• Ý nghĩa: Dùng quảng cáo trên trang web• Thuộc tính:

– ImageUrl: URL của hình ảnh cần được hiển thị– NavigateUrl: URL của trang web phải chuyển đến

control khi có sự kiện click.– AlternateText: Dòng văn bản hiển thị khi hình

không có sẳn– Keyword: loại quảng cáo– AdvertisementFile: file.xml – Height – Width

Page 43: Bài 3: SERVER CONTROL

<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile="~/XMLFile.xml" Height="20" Width="30" />

<?xml version="1.0" encoding="utf-8" ?><Advertisements> <Ad> <ImageUrl>Image/hinh1.gif</ImageUrl> <NavigateUrl>http://www.microsoft.com</NavigateUrl> <AlternateText>Alt Text</AlternateText> </Ad></Advertisements>

Page 44: Bài 3: SERVER CONTROL

Validation

• RequiredFieldValidator• Range Validator• RegularExpressionValidator• CompareValidator• CustomValidator• ValidationSummary

Page 45: Bài 3: SERVER CONTROL

RequiredFieldValidator

• Ý nghĩa: Yêu cầu người dùng phải nhập liệu• Cú pháp:

<asp:RequiredFieldValidator runat="server" ErrorMessage="Bạn phải nhập dữ liệu"

ControlToValidate="txtsoa" Display="Dynamic"

EnableClientScript =– true thì hiểu các script ở phía client– false thì không

Initialvalue = Giá trị khởi tạo />

Page 46: Bài 3: SERVER CONTROL

Range Validator

• Ý nghĩa: – Kiểm tra giới hạn nhập liệu– Giá trị nhập phải nằm trong khoảng giới hạn:

• giới hạn này có thể được đưa vào lúc thiết kế • hoặc so sánh với các control khác trên trang web

• Cú pháp:

<asp:RangeValidator id="RangeValidator1" runat="server“

errorMessage = "Content_Message"

controlToValidate = " input_Control"

display="static“ type = “Integer"

minimumValue = minValue

maximumValue = maxValue />

Page 47: Bài 3: SERVER CONTROL

RegularExpressionValidator

• Ý nghĩa: – Kiểm tra dữ liệu nhập với khuôn biểu thức mẫu

(RegularExpression) đã được định nghĩa trước– Visual Studio .NET cung cấp các khuôn biểu thức mẫu

• Cú pháp:<asp:RegularExpressionValidator runat="server"

ErrorMessage="thông báo" ControlToValidate="Id của control cần kiểm tra "

Display="Dynamic" ValidationExpression="biểu thức định dạng" />

Page 48: Bài 3: SERVER CONTROL

• Xác định file ảnh: "^([0-9a-zA-Z_\-~ :\\])+(.jpg|.JPG|.jpeg|.JPEG|.bmp|.BMP|.gif|.GIF|.png"

• Xác định số: "^\d+$" hoặc "^\d{n}"

• Ký tự là số: "[0-9]+"

• Lưu ý: *, ?

Page 49: Bài 3: SERVER CONTROL

CompareValidator

• Ý nghĩa: So sánh dữ liệu nhập với một trị hoặc hằng cho trước hoặc một giá trị trong dữ liệu

• Cú pháp:<asp:CompareValidator runat="server"

ErrorMessage="errormessage" ControlToValidate= " Id của control cần kiểm tra " ControlToCompare= " Id của control kiểm tra "

Type="Integer" Operator="Equal"

ValueToCompare= "giá trị" />

Page 50: Bài 3: SERVER CONTROL

CustomValidator• Ý nghĩa: Kiểm tra tính hợp lệ dữ liệu của một

control theo một yêu cầu, một ràng buộc nào đó• Cú pháp:<asp:CustomValidator ID="CustomValidator1" runat="server"

ErrorMessage="errormessage" ControlToValidate="tên ID cần kiểm tra"ClientValidationFunction: thuộc tính này nó chứa một

tên hàm, mà hàm này được lập trình ở client (javascript)onservervalidate="CustomValidator1_ServerValidate" />protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) { if (args.Value.Length>5) { args.IsValid = true; } else { args.IsValid = false; } }

Page 51: Bài 3: SERVER CONTROL

ValidationSummary

• Ý nghĩa: – Cho phép bạn liệt kê tất cả các các lỗi kiểm tra trên trang từ

những điều khiển validator vào một vị trí. – Điều khiển này đặc biệt tiện ích với Form có độ rộng lớn

• Cú pháp:<asp:ValidationSummary runat="server" ID="validchung"/>

• Thuộc tính:– DisplayMode: Cho phép bạn chỉ rõ định dạng hiển thị lỗi, nó

có thể là các giá trị như BulletList, List, và SingleParagraph– HeaderText: Cho phép bạn hiển thị tiêu đề tóm tắt cho các lỗi– ShowMessageBox: Cho hiện thị một popup thông báo– ShowSummary: Cho phép bạn ẩn ValidationSummary trên

trang.

Page 52: Bài 3: SERVER CONTROL

Wizard

• Ý nghĩa: Tạo các bước để dẫn dắt người dùng qua �một dãy màn hình nhằm thu thập thông tin

• Các thuộc tính quan trọng:– WizardStep– StepType : Start; Step; Finish; Complete

• Các sự kiện:– Onfinishbuttonclick: Xảy ra khi nút Finish được

Click– OnActiveStepChanged: Xảy ra khi thay đổi các

bước hiển thị

Page 53: Bài 3: SERVER CONTROL

Tạo ứng dụng

• Viết code cho các <asp:WizardStep ...>

• Viết code cho sự kiện Onfinishbuttonclick

13

2

4

5

Page 54: Bài 3: SERVER CONTROL

3.3. Client-Side Callback

• Sinh viên tự nghiên cứu