2.asp.net server controls - asp.net web forms

77
ASP.NET Server Controls Web Controls. HTML Controls. HTML Escaping Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer www.nakov.com aspnetcourse.telerik.com

Upload: telerik-software-academy

Post on 18-Nov-2014

6.659 views

Category:

Education


1 download

DESCRIPTION

This is presentation about ASP.NET Server Controls, part of the free ASP.NET Web Forms Course in Telerik Academy. Telerik Software Academy: http://aspnetcourse.telerik.com The website and all video materials are in Bulgarian Table of contents: Controls Class Hierarchy; HTML Server Controls; Web Server Controls; Web Server Control Life Cycle; HTML escaping; ASP.NET server controls; Example of ASP.NET server controls; ASP.NET Web Forms Course @ Telerik Academy http://aspnetcourse.telerik.com

TRANSCRIPT

Page 1: 2.ASP.NET Server Controls - ASP.NET Web Forms

ASP.NET Server Controls

Web Controls. HTML Controls.HTML Escaping

Svetlin Nakov

Telerik Software Academyacademy.telerik.com

Technical Trainerwww.nakov.com

aspnetcourse.telerik.com

Page 2: 2.ASP.NET Server Controls - ASP.NET Web Forms

Table of Contents1. Controls Class Hierarchy

2. HTML Server Controls

3. Web Server Controls Basic Web Controls Validation Controls List Controls Rich Controls

4. Web Server Control Life Cycle

5. HTML Escaping2

Page 3: 2.ASP.NET Server Controls - ASP.NET Web Forms

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>…

3

Page 4: 2.ASP.NET Server Controls - ASP.NET Web Forms

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

4

Page 5: 2.ASP.NET Server Controls - ASP.NET Web Forms

Controls – Class Hierarchy

Page 6: 2.ASP.NET Server Controls - ASP.NET Web Forms

Controls – Class Hierarchy

System.Web.UI.Control Base for all controls

Properties – ID, Page, ViewState, Context, ClientID, Controls

Methods – Render(HtmlTextWriter writer)

6

Page 7: 2.ASP.NET Server Controls - ASP.NET Web Forms

Controls – Class Hierarchy (2)

System.Web.UI.HtmlControls.HtmlControl

7

Page 8: 2.ASP.NET Server Controls - ASP.NET Web Forms

Controls – Class Hierarchy (3)

System.Web.UI.WebControls.WebControl

System.Web.UI.TemplateControl

8

Page 9: 2.ASP.NET Server Controls - ASP.NET Web Forms

HTML Server Controls

Page 10: 2.ASP.NET Server Controls - ASP.NET Web Forms

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:

10

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

Page 11: 2.ASP.NET Server Controls - ASP.NET Web Forms

HTML Server Control – Example

11

<%@ 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>

Page 12: 2.ASP.NET Server Controls - ASP.NET Web Forms

HTML Server Controls

Live Demo

Page 13: 2.ASP.NET Server Controls - ASP.NET Web Forms

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="…" /> ...

13

Page 14: 2.ASP.NET Server Controls - ASP.NET Web Forms

HTML Server Control Classes (2)

HtmlGenericControl Used for all other HTML elements

<p> <div> <span> <meta> <body> …

14

Page 15: 2.ASP.NET Server Controls - ASP.NET Web Forms

HtmlGenericControl – Example

15

<%@ 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>

Page 16: 2.ASP.NET Server Controls - ASP.NET Web Forms

HTML Generic Controls

Live Demo

Page 17: 2.ASP.NET Server Controls - ASP.NET Web Forms

Web Server Controls

Page 18: 2.ASP.NET Server Controls - ASP.NET Web Forms

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

18

Page 19: 2.ASP.NET Server Controls - ASP.NET Web Forms

Web Server Controls – Features

Rich functionality

Type-safe programming capabilities

Automatic Web browser detection

AutoPostBack

Sumbit when the focus is lost

Support for themes

19

Page 20: 2.ASP.NET Server Controls - ASP.NET Web Forms

Web Server Controls - Syntax

20

tag_prefix determines

unique namespace for

the web control

The name of the control

Attributes are properties of

the Web control

Mandatory attribute

runat="server"

<tag_prefix:controlname attributes runat="server"/>

Page 21: 2.ASP.NET Server Controls - ASP.NET Web Forms

Web Server Control – Example

21

<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;}

Page 22: 2.ASP.NET Server Controls - ASP.NET Web Forms

Web Server ControlsLive Demo

Page 23: 2.ASP.NET Server Controls - ASP.NET Web Forms

System.Web.UI. WebControls.WebContr

ol The WebControl class defines properties, events and methods for all Web controls

Control the appearance BackColor ForeColor BorderWidth BorderStyle BorderColor

23

Page 24: 2.ASP.NET Server Controls - ASP.NET Web Forms

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

24

Page 25: 2.ASP.NET Server Controls - ASP.NET Web Forms

Web Server ControlsBasic Web Controls

Page 26: 2.ASP.NET Server Controls - ASP.NET Web Forms

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>

<a href="…"></a>

<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">

26

Page 27: 2.ASP.NET Server Controls - ASP.NET Web Forms

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

27

Page 28: 2.ASP.NET Server Controls - ASP.NET Web Forms

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

28

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.

Page 29: 2.ASP.NET Server Controls - ASP.NET Web Forms

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

29

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.

Page 30: 2.ASP.NET Server Controls - ASP.NET Web Forms

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

30

Page 31: 2.ASP.NET Server Controls - ASP.NET Web Forms

Basic Web Controls – Buttons (2)

Events Click Command

CommandName and CommandArgument are passed to code behind

31

Page 32: 2.ASP.NET Server Controls - ASP.NET Web Forms

Basic Web Controls – Buttons (3)

Different button types Button

Creates a push button

Submit button by default

32

Page 33: 2.ASP.NET Server Controls - ASP.NET Web Forms

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

33

Page 34: 2.ASP.NET Server Controls - ASP.NET Web Forms

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

34

Page 35: 2.ASP.NET Server Controls - ASP.NET Web Forms

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

35

Page 36: 2.ASP.NET Server Controls - ASP.NET Web Forms

Buttons – Example

36

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

<!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 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 />

Page 37: 2.ASP.NET Server Controls - ASP.NET Web Forms

Buttons – Example (2)

37

<asp:LinkButton ID="LinkButtonEx" runat="server" OnClick="OnBtnClick" Text="Link Button" CommandName="LinkButtonEx" OnCommand="OnCommand" /> <br /> <asp:ImageButton ID="ImageButtonEx" runat="server" CommandName="ImageButtonEx" ImageUrl="~/images/DotNet_Logo_Small.gif" OnCommand="OnCommand" OnClick="OnBtnClick" /> <br /> <asp:Label ID="LabelMessage" runat="server" Text=""></asp:Label> </form></body></html>

Page 38: 2.ASP.NET Server Controls - ASP.NET Web Forms

38

ButtonsLive Demo

Page 39: 2.ASP.NET Server Controls - ASP.NET Web Forms

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

39

Page 40: 2.ASP.NET Server Controls - ASP.NET Web Forms

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)

40

Page 41: 2.ASP.NET Server Controls - ASP.NET Web Forms

PanelsLive Demo

Page 42: 2.ASP.NET Server Controls - ASP.NET Web Forms

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 Control42

Page 43: 2.ASP.NET Server Controls - ASP.NET Web Forms

Basic Web Controls – CheckBox

Select between checked / unchecked

Properties Checked Text – control caption

AutoPostBack automatically posts back the page

when control state is changed

43

Page 44: 2.ASP.NET Server Controls - ASP.NET Web Forms

Basic Web Controls – CheckBox (2)

CausesValidation – whether validation is performed

ValidationGroup – which validation group to be validated

Events CheckChanged

44

Page 45: 2.ASP.NET Server Controls - ASP.NET Web Forms

Basic Web Controls – RadioButton

Creates a radio button on the Web Forms page

Properties Text GroupName – allow a mutually

exclusive selection from the group

45

Page 46: 2.ASP.NET Server Controls - ASP.NET Web Forms

Validation ControlsPerforming Control Validation

Page 47: 2.ASP.NET Server Controls - ASP.NET Web Forms

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

47

Page 48: 2.ASP.NET Server Controls - ASP.NET Web Forms

Validation Controls (2) Most important validation controls:

RequiredFieldValidator RangeValidator CompareValidator RegularExpressionValidator CustomValidator ValidationSummary

48

Page 49: 2.ASP.NET Server Controls - ASP.NET Web Forms

Validation Controls

Live Demo

Page 50: 2.ASP.NET Server Controls - ASP.NET Web Forms

List ControlsDisplaying Lists of Items

Page 51: 2.ASP.NET Server Controls - ASP.NET Web Forms

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

51

Page 52: 2.ASP.NET Server Controls - ASP.NET Web Forms

List Controls (2) ListBox CheckBoxList RadioButtonList Repeater DataList GridView DropDownList

52

Page 53: 2.ASP.NET Server Controls - ASP.NET Web Forms

List ControlsLive Demo

Page 54: 2.ASP.NET Server Controls - ASP.NET Web Forms

Web Server ControlsRich Controls

Page 55: 2.ASP.NET Server Controls - ASP.NET Web Forms

Rich Controls Task-specific controls Built with multiple HTML elements Rich functionality Examples:

Calendar AdRotator

55

Page 56: 2.ASP.NET Server Controls - ASP.NET Web Forms

Web Server

Controls – Lifecycle

Page 57: 2.ASP.NET Server Controls - ASP.NET Web Forms

Phases Init ViewState Load Send Postback Change Notification Handle Postback events PreRender Save State Render Dispose Unload

57

Page 58: 2.ASP.NET Server Controls - ASP.NET Web Forms

Phases - Initialize

Control initialize settings needed during incoming web request

Init event (OnInit method)

58

Page 59: 2.ASP.NET Server Controls - ASP.NET Web Forms

Phases – Load View State

At the end of this phase ViewState property is automatically populated

Override LoadViewState method to customize state restoration

LoadViewState method

59

Page 60: 2.ASP.NET Server Controls - ASP.NET Web Forms

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)

60

Page 61: 2.ASP.NET Server Controls - ASP.NET Web Forms

Phases – Send Postback Change Notification

Raise change events in response to state changes between previous and current postbacks

RaisePostDataChangedEvent method IPostBackDataHandler should be implemented

61

Page 62: 2.ASP.NET Server Controls - ASP.NET Web Forms

Phases – Handle Postback Events

Handle client-side events caused postback

Raise appropriate events on the server

RaisePostBackEvent method IPostBackEventHandler should be implemented

62

Page 63: 2.ASP.NET Server Controls - ASP.NET Web Forms

Phases – PreRender Perform any updates before the control is rendered

Changes made in this phase can be saved

PreRender event (OnPreRender method)

63

Page 64: 2.ASP.NET Server Controls - ASP.NET Web Forms

Phases – Save State ViewState property is persisted Send to the client and back as a hidden field

SaveViewState method

64

Page 65: 2.ASP.NET Server Controls - ASP.NET Web Forms

Phases – Render Generates the output which will be send to the client

Any changes to controls state made here are lost

Render() method

65

Page 66: 2.ASP.NET Server Controls - ASP.NET Web Forms

Phases – Dispose Final clean up Expensive resources should be released

Dispose() method

66

Page 67: 2.ASP.NET Server Controls - ASP.NET Web Forms

Phases – Unload Final clean up Usually clean up is performed in previous phase so this event is not handled

UnLoad event (OnUnLoad() method)

67

Page 68: 2.ASP.NET Server Controls - ASP.NET Web Forms

Controls Lifecycl

eLive Demo

Page 69: 2.ASP.NET Server Controls - ASP.NET Web Forms

HTML Escaping

Page 70: 2.ASP.NET Server Controls - ASP.NET Web Forms

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

70

Page 71: 2.ASP.NET Server Controls - ASP.NET Web Forms

Character Encoding Each character could be presented as

HTML entity escaping sequence Numeric character references:

'λ' is &#955;, &#x03BB; or &#X03bb; Named HTML entities:

'λ' is &lambda; '<' is &lt; '>' is &gt; '&' is &amp; " (double quote) is &quot;

71

Page 72: 2.ASP.NET Server Controls - ASP.NET Web Forms

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

72

Page 73: 2.ASP.NET Server Controls - ASP.NET Web Forms

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!

73

Page 74: 2.ASP.NET Server Controls - ASP.NET Web Forms

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:

74

<%response.write(Server.HTMLEncode("The image tag: <img>"))%>

The image tag: &lt;img&gt;

The image tag: <img>

Page 75: 2.ASP.NET Server Controls - ASP.NET Web Forms

HTML EscapingLive Demo

Page 76: 2.ASP.NET Server Controls - ASP.NET Web Forms

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезания

ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGap

free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно

?

? ? ??

?? ?

?

?

?

??

?

?

? ?

Questions?

?

ASP.NET Server Controls

http://academy.telerik.com

Page 77: 2.ASP.NET Server Controls - ASP.NET Web Forms

Free Trainings @ Telerik Academy

ASP.NET Web Forms Course aspnetcourse.telerik.com

Telerik Software Academy academy.telerik.com

Telerik Academy @ Facebook facebook.com/TelerikAcademy

Telerik Software Academy Forums forums.academy.telerik.com