Download presentation
Presentation is loading. Please wait.
1
ASP.NET Web Controls and HTML Controls
* 9/15/201807/16/96 ASP.NET Web Controls and HTML Controls Svetlin Nakov Telerik Corporation (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
2
Table of Contents Controls Class Hierarchy HTML Server Controls
* 9/15/201807/16/96 Table of Contents Controls Class Hierarchy HTML Server Controls Web Server Controls Basic Web Controls Validation Controls List Controls Rich Controls Web Server Control Life Cycle HTML Escaping (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
3
What is ASP.NET Server Control?
* 9/15/201807/16/96 What is ASP.NET Server Control? ASP.NET server controls The smallest ASP.NET Component Wrap an HTML UI element, or more complex UI Component-oriented programming model Executed and rendered at the server side Example of ASP.NET server controls: <asp:Button> <input type="submit"> <asp:Label> <span> <asp:GridView> <table><tr><td>… Бележки на автора: (1) ASP.NET Server Controls ASP.NET server контролата е компонент, който се изпълнява на сървъра и обвива потребителски интерфейс и друга функционалност. Server контролите се използват в ASP.NET страниците и code-behind класовете. Server контролите включват бутони, текстови полета (text boxes), drop-down списъци и други. Всички server контроли имат атрибутите id и text, както и runat="server" атрибута. Последният атрибут означава, че логиката (кода) на контролата се изпълнява на сървъра, а не при клиента, както е с HTML елементите. (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
4
What is ASP.NET Server Control ?(2)
* 9/15/201807/16/96 What is ASP.NET Server Control ?(2) Mandatory properties for all server controls: runat="server" ID="…" Programming model based on events Each user interaction causes and event Programmer decides which events to handle Browser-specific HTML is generated Controls deliver appropriate HTML depending on browser type Обработчик на събитие е това, което се случва, когато клиентът цъкне на бутон или списък. Кодът, който се изпълнява, се слага в така наречените събитийни event процедури. Вие като програмист на уеб форми решавате кои event процедури се асоциират с контролата. Общ модел В ASP.NET server контролите са базирани на общ модел и като резултат споделят голям брой атрибути. Например, когато трябва да се смени цветът на фона на контрола, винаги се използва едно и също свойството BackColor без значение коя е контролата. Следният HTML код, който описва server контрола, показва някои типични атрибути: <asp:Button id="Button1" runat="server" BackColor="red" Width="238px" Height="25px" Text="Web control"></asp:Button> Browser-specific HTML Когато една страница се подготвя за клиента (rendering), сървърната контрола решава какъв е браузърът, подал заявката, и доставя съответния HTML код. Например, ако браузърът поддържа възможност за четене на скрипт (client-side scripting), какъвто е Internet Explorer version 4.0 или по-нова, контролите създават такъв клиентски скрипт (client-side script), за да си имплементират част от функционалността директно на клиентския браузър. Ако не поддържа клиентски скрипт (client-side script), контролите създават код, изпълняван на сървъра (server-side код), който имплементира същата функционалност, но се правят повече заявки до сървъра, за да се получи същата функционалност. Следният код е отрязък от ASP.NET уеб форма, която ще създаде текстово поле (text box) със следния текст: "Enter your Username": <asp:TextBox id="TextBox1" runat="server" Width="238px" Height="25px">Enter your Username</asp:TextBox> Когато тази страница се достъпва от потребител с Internet Explorer 6, средата за управление (CLR) създава следния HTML код: <input name="TextBox1" type="text" value="Enter your Username" id="TextBox1" style="height:25px;width:238px" /> Server контролите създават ad hoc (специализиран, с ясната представа какви са възможностите на браузъра) HTML код за съответния клиент. Така можете да пишете за най-новите браузъри, без да се притеснявате от клиенти със стари версии (или липсваща функционалност) на браузърите си. (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
5
Controls – Class Hierarchy
* 9/15/201807/16/96 Controls – Class Hierarchy (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
6
Controls – Class Hierarchy
System.Web.UI.Control Base for all controls Properties – ID, Page, ViewState, Context, ClientID, Controls Methods – Render(HtmlTextWriter writer)
7
Controls – Class Hierarchy (2)
System.Web.UI.HtmlControls.HtmlControl
8
Controls – Class Hierarchy (3)
System.Web.UI.WebControls.WebControl System.Web.UI.TemplateControl
9
HTML Server Controls * 9/15/201807/16/96
(c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
10
HTML Server Controls HTML server controls are very simple extension of Control class Look like traditional HTML Defined by runat="server" Simple HTML seems like text on the server If an HTML element is converted to HTML server control, a server side object is associated with it Valid only inside a Web form tag: <form runat="server">…</form>
11
HTML Server Control – Example
Page Language="C#" %> <script language="c#" runat="server"> void ButtonSubmit_Click(Object sender, EventArgs e) { Response.Write("Value:<b>"+TextField.Value+"</b>"); } </script> <html> <head><title>HTML Server Controls</title></head> <body> <form id="formMain" runat="server"> <input id="TextField" type="text" runat="server" /> <input id="ButtonSubmit" type="button" runat="server" value="Submit" onserverclick="ButtonSubmit_Click" /> </form> </body> </html>
12
HTML Server Controls Live Demo * 9/15/201807/16/96
(c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* 12##
13
HTML Server Control Classes
* 9/15/201807/16/96 HTML Server Control Classes HtmlForm – <form>…</form> HtmlInputText – <input type="text"> HtmlButton – <input type="button" /> HtmlAnchor – <a href="…">…</a> HtmlSelect – <input type="select"> HtmlTable, HtmlTableCell, HtmlTableRow – <table><tr><td>…</td></tr></table> HtmlImage – <img src="…" /> ... HtmlAnchor controls the <a> element. HtmlButton controls the <input type="button"> element. HtmlForm controls the <form> element. HtmlSelect controls the <select> element. HtmlTable controls the <table> element. HtmlTableCell controls the <td> element. HtmlTableRow controls the <tr> element. HtmlTextArea controls the <textarea> element. HtmlInputButton controls the <input type="button"> element. HtmlInputCheckBox controls the <input type="checkbox"> element. HtmlInputFile controls the <input type="file"> element. HtmlInputHidden controls the <input type="hidden"> element. HtmlInputImage controls the <input type="image"> element. HtmlInputRadioButton controls the <input type="radio"> element. HtmlInputText controls the <input type="text"> element. HtmlImage controls the <img> element. (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
14
HTML Server Control Classes (2)
* 9/15/201807/16/96 HTML Server Control Classes (2) HtmlGenericControl Used for all other HTML elements <p> <div> <span> <meta> <body> … (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
15
HtmlGenericControl – Example
Page Language="C#" %> <script runat="server"> void Page_Load(Object sender, EventArgs e) { this.MetaInfo.Attributes["name"] = "description"; this.MetaInfo.Attributes["content"] = "The page was generated on: " + DateTime.Now.ToString(); } </script> <html> <head> <meta id="MetaInfo" runat="server" /> </head> <body> <form id="formMain" runat="server">…</form> </body> </html>
16
HTML Generic Controls Live Demo
17
Web Server Controls * 9/15/201807/16/96
(c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
18
* 9/15/201807/16/96 Web Server Controls Web server controls are server UI controls that abstract the common HTML elements Have own lifecycle and functionality Come with .NET Framework Located in System.Web.UI.WebControls namespace, inherit from the WebControl class HTML Abstraction Rendered HTML tags are quite different from the design-time markup (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
19
Web Server Controls – Features
* 9/15/201807/16/96 Web Server Controls – Features Rich functionality Type-safe programming capabilities Automatic Web browser detection AutoPostBack Sumbit when the focus is lost Support for themes (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
20
Web Server Controls - Syntax
* 9/15/201807/16/96 Web Server Controls - Syntax tag_prefix determines unique namespace for the web control Attributes are properties of the Web control <tag_prefix:controlname attributes runat="server"/> Mandatory attribute runat="server" The name of the control (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
21
Web Server Control – Example
<form id="formMain" runat="server"> <asp:Label ID="LabelResult" runat="server" Text="" Visible="false" /> <asp:TextBox ID="TextBoxInput" runat="server" /> <asp:Button ID="ButtonSubmit" runat="server" Text="Submit" OnClick="ButtonSubmit_Click" /> </form> … protected void ButtonSubmit_Click( object sender, EventArgs e) { this.LabelResult.Text = "You entered: " + this.TextBoxInput.Text; this.LabelResult.Visible = true; }
22
Web Server Controls Live Demo
23
System.Web.UI. WebControls.WebControl
* 9/15/201807/16/96 System.Web.UI. WebControls.WebControl The WebControl class defines properties, events and methods for all Web controls Control the appearance BackColor ForeColor BorderWidth BorderStyle BorderColor (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
24
System.Web.UI. WebControls.WebControl (2)
* 9/15/201807/16/96 System.Web.UI. WebControls.WebControl (2) Control the behavior Enabled Visible TabIndex ToolTip … Not all controls support all these properties See the documentation for details (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
25
Web Server Controls Basic Web Controls * 9/15/201807/16/96
(c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
26
Basic Web Controls HTML
* 9/15/201807/16/96 Basic Web Controls HTML <asp:button> <input type="submit"> <asp:checkbox> <input type="checkbox"> <asp:hyperlink> <a href="…"></a> <asp:image> <img src="…"> <asp:imagebutton> <input type="image"> <asp:linkButton> <asp:label> <span>…</span> <asp:listbox> <select size="5"></select> <asp:panel> <div>…</div> <asp:radiobutton> <input type="radio"> <asp:table> <table>…</table> <asp:textbox> <input type="text"> Вътрешни контроли HTML Basic Web server контроли отговарят на прости HTML елементи. Някои от често използваните основни Web server контроли са показани на таблицата. (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
27
Basic Web Controls: TextBox
* 9/15/201807/16/96 Basic Web Controls: TextBox Creates single-line or multiline text-box Lets the user to enter text Properties Text TextMode – SingleLine, MultiLine, Password MaxLength ReadOnly AutoPostBack Events TextChanged – combined with AutoPostBack (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
28
Basic Web Controls: Label
* 9/15/201807/16/96 Basic Web Controls: Label Display static text in a <span> block Allows programmatically to manipulate it Properties Text AssociatedControlID – on click focus goes to the specified control Events TextChanged – combined with AutoPostBack CAUTION: the Text is NOT HTML encoded before it is displayed in the Label control. This make it possible to embed script within HTML tags in the text. (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
29
Basic Web Controls: Literal
* 9/15/201807/16/96 Basic Web Controls: Literal Display static text Allows programmatically to manipulate it Unlike the Label control, Literal does not let you apply styles to its content Properties Text Renders the Text property value directly CAUTION: the Text is NOT HTML encoded before it is displayed in the Literal control. This make it possible to embed script within HTML tags in the text. (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
30
Basic Web Controls – Buttons
* 9/15/201807/16/96 Basic Web Controls – Buttons Implement IButtonControl Properties Text – button's title CommandName – pass a command CommandArgument – pass command arguments PostBackUrl – posts back to specified page CausesValidation – perform validation or not ValidationGroup – which validation group to be validated (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
31
Basic Web Controls – Buttons (2)
* 9/15/201807/16/96 Basic Web Controls – Buttons (2) Events Click Command CommandName and CommandArgument are passed to code behind (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
32
Basic Web Controls – Buttons (3)
* 9/15/201807/16/96 Basic Web Controls – Buttons (3) Different button types Button Creates a push button Submit button by default (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
33
Basic Web Controls – Buttons (4)
* 9/15/201807/16/96 Basic Web Controls – Buttons (4) Different button types Command Button Has command name associated (CommandName property) Programmatically determine which button is clicked in Command event handles Used in templated controls, e.g. GridView (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
34
Basic Web Controls – Buttons (5)
* 9/15/201807/16/96 Basic Web Controls – Buttons (5) Different button types LinkButton Same functionality as Button Renders as hyperlink Use Hyperlink if you want to link to another page Renders JavaScript on the client browser (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
35
Basic Web Controls – Buttons (6)
* 9/15/201807/16/96 Basic Web Controls – Buttons (6) Different button types ImageButton Display an image that responds on mouse click ImageURL – URL to displayed image Both Click and Command events are raised (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
36
Buttons – Example Page Language="C#" AutoEventWireup="true" CodeFile="Buttons.aspx.cs" Inherits="Buttons" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="formMain" runat="server"> <asp:Button ID="ButtonEx" CommandName="ButtonEx" runat="server" OnClick="OnBtnClick" OnCommand="OnCommand" Text="Normal Button" /> <br />
37
Buttons – Example (2) <asp:LinkButton ID="LinkButtonEx"
runat="server" OnClick="OnBtnClick" Text="Link Button" CommandName="LinkButtonEx" OnCommand="OnCommand" /> <br /> <asp:ImageButton ID="ImageButtonEx" CommandName="ImageButtonEx" ImageUrl="~/images/DotNet_Logo_Small.gif" OnCommand="OnCommand" OnClick="OnBtnClick" /> <asp:Label ID="LabelMessage" runat="server" Text=""></asp:Label> </form> </body> </html>
38
Buttons Live Demo * 9/15/201807/16/96
(c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* 38##
39
Basic Web Controls – Panel
* 9/15/201807/16/96 Basic Web Controls – Panel The Panel control Container for other controls Rendered as <div> Useful for: Displaying and hiding groups of controls Generating and inserting controls at runtime (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
40
Basic Web Controls – Panel(2)
Properties ScrollBars – modify visibility and position of scroll bars Wrap – value indicating whether the content wraps within the panel GroupingText – caption for the group of controls that is contained in panel control DefaultButton – button to be pressed by default (Enter)
41
* * 9/15/201807/16/96 9/15/201807/16/96 Panels Live Demo (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* 41##
42
Basic Web Controls – PlaceHolder
The PlaceHolder control Reserves a space in the page control hierarchy Used to add controls to the page at runtime Does not produce any visible output Controls Use it to add, insert or remove controls from PlaceHolder Control
43
Basic Web Controls – CheckBox
* 9/15/201807/16/96 Basic Web Controls – CheckBox Select between checked / unchecked Properties Checked Text – control caption AutoPostBack automatically posts back the page when control state is changed (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
44
Basic Web Controls – CheckBox (2)
CausesValidation – whether validation is performed ValidationGroup – which validation group to be validated Events CheckChanged
45
Basic Web Controls – RadioButton
Creates a radio button on the Web Forms page Properties Text GroupName – allow a mutually exclusive selection from the group
46
* Performing Control Validation
9/15/201807/16/96 Validation Controls Performing Control Validation (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
47
Validation Controls The ASP.NET Web forms validation controls
Validate the values that are entered into other controls of the page Two modes of validation Client-side validation Server-side validation Validation is performed at page submit
48
Validation Controls (2)
Most important validation controls: RequiredFieldValidator RangeValidator CompareValidator RegularExpressionValidator CustomValidator ValidationSummary
49
Validation Controls Live Demo * 9/15/201807/16/96
(c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
50
* Displaying Lists of Items
9/15/201807/16/96 List Controls Displaying Lists of Items (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
51
List Controls List Web controls
Display list of items, e.g. table of rows Support binding to a collection Display rows of data in templated format Expose DataSourceID, DataSource, DataMember properties Bind to collection that support IEnumerable, ICollection or IListSource
52
List Controls (2) ListBox CheckBoxList RadioButtonList Repeater
DataList GridView DropDownList
53
List Controls Live Demo * 9/15/201807/16/96
(c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
54
Web Server Controls Rich Controls * 9/15/201807/16/96
(c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
55
Rich Controls Task-specific controls Built with multiple HTML elements
Rich functionality Examples: Calendar AdRotator
56
Web Server Controls – Lifecycle
* 9/15/201807/16/96 Web Server Controls – Lifecycle (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
57
Phases Init ViewState Load Send Postback Change Notification
Handle Postback events PreRender Save State Render Dispose Unload
58
Phases - Initialize Control initialize settings needed during incoming web request Init event (OnInit method)
59
Phases – Load View State
At the end of this phase ViewState property is automatically populated Override LoadViewState method to customize state restoration LoadViewState method
60
Phases – Load Perform actions common to all requests
Server controls in the tree are created and initialized Control state from previous round trip is restored including client – side data Load event (OnLoad method)
61
Phases – Send Postback Change Notification
Raise change events in response to state changes between previous and current postbacks RaisePostDataChangedEvent method IPostBackDataHandler should be implemented
62
Phases – Handle Postback Events
Handle client-side events caused postback Raise appropriate events on the server RaisePostBackEvent method IPostBackEventHandler should be implemented
63
Phases – PreRender Perform any updates before the control is rendered
Changes made in this phase can be saved PreRender event (OnPreRender method)
64
Phases – Save State ViewState property is persisted
Send to the client and back as a hidden field SaveViewState method
65
Phases – Render Generates the output which will be send to the client
Any changes to controls state made here are lost Render() method
66
Phases – Dispose Final clean up Expensive resources should be released
Dispose() method
67
Phases – Unload Final clean up
Usually clean up is performed in previous phase so this event is not handled UnLoad event (OnUnLoad() method)
68
Controls Lifecycle Live Demo * 9/15/201807/16/96
(c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* 68##
69
* 9/15/201807/16/96 HTML Escaping (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
70
What is HTML Escaping? HTML escaping is the act of replacing special characters with their HTML entities Escaped characters are interpreted as character data instead of mark up Typical characters to escape <, > – start / end of HTML tag & – start of character entity reference ', " – text in single / double quotes …
71
Character Encoding Each character could be presented as HTML entity escaping sequence Numeric character references: 'λ' is λ, λ or λ Named HTML entities: 'λ' is λ '<' is < '>' is > '&' is & " (double quote) is "
72
XSS Attack Cross-site scripting (XSS) is a common security vulnerability in Web applications Web application is let to display a JavaScript code that is executed at the client's browser Crackers could take control over sessions, cookies, passwords, and other private data How to prevent from XSS? ALWAYS validate the user input Perform HTML escaping when displaying text data in a Web control
73
What Offers ASP.NET? ValidateRequest attribute of Page directive
Checks all input data against a hard-coded list of potentially dangerous values The default is true Using it could harm the normal work on some applications E.g. a user posts JavaScript code in a forum Escaping is better way to handle the problem!
74
What Offers ASP.NET ? (2) HttpServerUtility.HtmlEncode
HTML encodes a string and returns the encoded string Page.Server is instance of HttpServerUtility The following script Output: Web browser renders the following: <%response.write(Server.HTMLEncode("The image tag: <img>"))%> The image tag: <img> The image tag: <img>
75
HTML Escaping Live Demo * 9/15/201807/16/96
(c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* (c) 2005 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* 75##
76
ASP.NET Web Controls and HTML Controls
Questions?
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.