dynamic web programming building web …€¦ · page returns a reference to the page object that...

31
BUILDING WEB APPLICATIONS USING ASP.NET, AJAX AND JAVASCRIPT Dynamic Web Programming

Upload: vokhanh

Post on 19-Jul-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

BUILDING WEB APPLICATIONS USING

ASP.NET, AJAX AND JAVASCRIPT

Dynamic Web Programming

Page 2: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

AGENDA

5. ASP.NET Server Controls

5.1 Page Control Hierarchy

5.2 Types of Server Controls

5.3 Web Controls

5.4 List Controls

5.5 Input Validation Controls

5.6 Rich Controls

Page 3: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

Building Web Applications Using ASP.NET, AJAX And JavaScript

5. ASP.NET SERVER CONTROLS

Page 4: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.1 PAGE CONTROL HIERARCHY

ASP.NET controls are processed on the server and rendered in

HTML/JavaScript to the client in an object-oriented manner.

ASP.NET collects all controls on a page and renders them

according to the aspx markup specification.

Each control can also have child controls.

At the page level, ASP.NET added a controls collection that keeps

track of the controls on a

page (runat=“server”).

By looping through the

controls collection you can

examine each individual

control.

66

Page 5: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.1 PAGE CONTROL HIERARCHY

67

Page 6: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.1 PAGE CONTROL HIERARCHY

68

Page 7: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.1 PAGE CONTROL HIERARCHY

69

Page 8: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.2 TYPES OF SERVER CONTROLS

HTML Server Controls: Classes that wrap the standard HTML

elements. You can turn any general HTML tag into a server

control by adding the attribute runat=“server”.

Web Controls: These classes duplicate the functionalities of the

basic HTML elements but have a more consistent and

meaningful set of properties and methods. You have much more

programmatic control over those controls to build a rich UI

experience.

Rich Controls: These advanced controls have the ability to

generate a large amount of HTML markup and even client-side

JavaScript to create an interface.

Validation Controls: These controls allow you to build

sophisticated validation tools for all types of controls and

validation needs.

70

Page 9: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.2 TYPES OF SERVER CONTROLS

Data Controls: These controls include sophisticated grids and

lists to display large amount of data with support for advanced

features such as templating, editing, sorting, and pagination.

Navigation Controls: These controls are designed to display site

maps and allow the user to perform basic navigation tasks.

Login Controls: These controls support forms authentication, an

ASP.NET model for authenticating users against a database.

These are prebuilt controls having customizable login pages,

password recovery, and user creation wizard.

ASP.NET AJAX Controls: These controls allow you to use AJAX

techniques in your web pages without forcing you to write client-

side code.

There are other controls that do not translate into visible

controls such as DataSource, Panel, etc. controls.

71

Page 10: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.3 WEB CONTROLS

These controls are modeled after the HTML controls but contain

much more functionality.

Some web controls do not map to a single HTML control, but

instead generate

more complex

output made up of

several HTML tags

and JavaScript

code.

Properties of the

general

Control class

72

Property Description

ClientID Returns the identifier of the control, which is a unique name created by

ASP.NET at the time the page is instantiated.

Controls Returns the collection of child controls. You can use the Page.Controls

collection to get the top-level collection of controls on the page. Each

control in the Controls collection may contain its own child controls, and

those controls can hold still more controls of their own, and so on.

EnableVie

wState

Returns or sets a Boolean value indicating whether the control should

maintain its state across postbacks of its parent page. This property is

true by default.

ID Returns or sets the identifier of the control. In practice, this is the name

through which you can access the control from the server-side scripts or

the code-behind class.

Page Returns a reference to the page object that contains the control.

Parent Returns a reference to the control’s parent, which can be the page or

another container control.

Visible Returns or sets a Boolean value indicating whether the control should be

rendered. If false, the control is not just made invisible on the client—

instead, the corresponding HTML tag is not generated.

Page 11: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.3 WEB CONTROLS

Common methods of

the general Control

Class.

Web Control Class has

additional powerful

properties and

methods.

73

Method Description

DataBind() Binds the control and all of its child controls to the specified data source or

expression.

FindControl() Searches for a child control with a specific name in the current control and all

contained controls. If the child control is found, the method returns a reference of

the general type Control. You can then cast this control to the proper type.

HasControls() Returns a Boolean value indicating whether this control has any child controls. The

control must be a container tag to have child controls (such as a <div> tag).

Render() Writes the HTML output for the control based on its current state. You do not call

this method directly. Instead, ASP.NET calls it when the page is being rendered.

Properties Description

AccessKey Returns or sets the keyboard shortcut that allows the user to quickly navigate to the

control. For example, if set to A, the user can move the focus to this control by

pressing Alt+A.

BackColor Returns or sets the background color.

BorderColor Returns or sets the border color.

BorderStyle One of the values from the BorderStyle enumeration, including Dashed, Dotted,

Double, Groove, Ridge, Inset, Outset, Solid, and None.

BorderWidth Returns or sets the border width.

CssClass Returns or sets the CSS style to associate with the control. The CSS style can be

defined in a <style> section at the top of the page or in a separate CSS file referenced

by the page.

Enabled Returns or sets the control’s enabled state. If false, the control is usually rendered

grayed out and is not usable.

Font Returns an object with all the style information of the font used for the control’s text.

This property includes subproperties that can be set with the object-walker syntax

shown in this chapter.

ForeColor Returns or sets the foreground color—for example, that of the text of the control.

Height Returns or sets the control’s height.

TabIndex A number that allows you to control the tab order. The control with a TabIndex of 0

has the focus when the page first loads. Pressing Tab moves the user to the control

with the next lowest TabIndex, provided it is enabled.

Tooltip Displays a text message when the user hovers the mouse above the control.

Width Returns or sets the control’s width.

Page 12: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.3 WEB CONTROLS

Basic Web

controls

It also shows

the basic

generated HTML

output.

74

ASP.NET Tag Generated HTML Key Members

<asp:Button> <input type="submit"/>

<input type="button"/>

Text, CausesValidation, PostBackUrl, ValidationGroup, Click

event

<asp:CheckBox> <input type="checkbox"/> AutoPostBack, Checked, Text, TextAlign, CheckedChanged

event

<asp:FileUpload> <input type="file"> FileBytes, FileContent, FileName, HasFile, PostedFile,

SaveAs()

<asp:HiddenField> <input type="hidden"> Value

<asp:HyperLink> <a>...</a> ImageUrl, NavigateUrl, Target, Text

<asp:Image> <img/> AlternateText, ImageAlign, ImageUrl

<asp:ImageButton> <input type="image"/> CausesValidation, ValidationGroup, Click event

<asp:ImageMap> <map> HotSpotMode, HotSpots (collection), AlternateText,

ImageAlign, ImageUrl

<asp:Label> <span>...</span> Text, AssociatedControlID

<asp:LinkButton> <a><img/></a> Text, CausesValidation, ValidationGroup, Click event

<asp:Panel> <div>...</div> BackImageUrl, DefaultButton, GroupingText, HorizontalAlign,

Scrollbars, Wrap

<asp:RadioButton> <input type="radio"/> AutoPostBack, Checked, GroupName, Text, TextAlign,

CheckedChanged event

<asp:Table> <table>...</table> BackImageUrl, CellPadding, CellSpacing, GridLines,

HorizontalAlign, Rows (collection)

<asp:TableCell> <td>...</td> ColumnSpan, HorizontalAlign, RowSpan, Text, VerticalAlign,

Wrap

<asp:TableRow> <tr>...</tr> Cells (collection), HorizontalAlign, VerticalAlign

<asp:TextBox> <input type="text"/> or

<textarea>...</textarea>

AutoPostBack, Columns, MaxLength, ReadOnly, Rows, Text,

TextMode, Wrap, TextChanged event

Page 13: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.3 WEB CONTROLS

Web controls have two restrictions:

Every control must have an ending tag or use the empty (/>) syntax.

All web controls must be declared within a server-side form tag (and there

can be only one form per page).

75

Page 14: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.3 WEB CONTROLS

Using color values in ASP.NET. Use System.Drawing namespace.

Specify the argb (alpha, red, green, blue) value.

Use .NET predefined color name from the color class.

Use HTML color name (must use ColorTranslator class).

Font property refers to a full FontInfo object.

When using font properties in markup code,

use the object-walker syntax:

Every input control provides a Focus() method.

Server-side events exist for all web controls,

there are quite a few.

Use AutoPostback=True to fire event immediately.

Most common events: Click, Changed, Checked

76

Page 15: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.3 WEB CONTROLS

77

Page 16: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.3 WEB CONTROLS

78

Page 17: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.4 LIST CONTROLS

79

List controls are specialized web controls that generate list boxes, drop-down lists, and other repeating controls.

Either bound to a data source (database or hard-coded values) or programmatically filled with items.

All list controls support same base properties and methods.

Additionally, they inherited from the System.Web.UI.WebControls.ListControl class for special properties and methods (next slide).

Control Description

<asp:DropDownList> A drop-down list populated by a collection of

<asp:ListItem> objects. In HTML, it is

rendered by a <select> tag with the size="1"

attribute.

<asp:ListBox> A list box list populated by a collection of

<asp:ListItem> objects. In HTML, it is

rendered by a <select> tag with the size="x"

attribute, where x is the number of visible

items.

<asp:CheckBoxList> Its items are rendered as check boxes, aligned

in a table with one or more columns.

<asp:RadioButtonList> Like the <asp:CheckBoxList>, but the items

are rendered as radio buttons.

<asp:BulletedList> A static bulleted or numbered list. In HTML, it

is rendered using the <ul> or <ol> tags. You

can also use this control to create a list of

hyperlinks.

Page 18: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.4 LIST CONTROLS

80

Most common event: SelectedIndexChanged

Member Description

AutoPostBack If true, the form is automatically posted back when the user changes the current

selection.

Items Returns a collection of ListItem items (the items can also be added declaratively by

adding the <asp:ListItem> tag).

SelectedIndex Returns or sets the index of the selected item. For lists with multiple selectable items,

you should loop through the Items collection and check the Selected property of each

ListItem instead.

SelectedItem Returns a reference to the first selected ListItem. For lists with multiple selectable

items, you should loop through the Items collection and check the Selected property of

each ListItem instead.

DataSource You can set this property to an object that contains the information you want to display

(such as a DataSet, DataTable, or collection). When you call DataBind(), the list will be

filled based on that object.

DataMember Used in conjunction with data binding when the data source contains more than one

table (such as when the source is a DataSet). The DataMember identifies which table

you want to use.

DataTextField Used in conjunction with data binding to indicate which property or field in the data

source should be used for the text of each list item.

DataValueField Used in conjunction with data binding to indicate which property or field in the data

source should be used for the value attribute of each list item (which isn’t displayed

but can be read programmatically for future reference).

DataTextFormatString Sets the formatting string used to render the text of the list item (according to the

DataTextField property).

Page 19: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.4 LIST CONTROLS

81

Page 20: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.4 LIST CONTROLS

82

Page 21: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.5 INPUT VALIDATION CONTROLS

Applications need to validate data. Web applications are no

exception.

Ideally, validation takes place on the client side.

But is always a good idea to also perform server-side validation.

Hackers can remove or bypass client-side JavaScript code!

Writing validation

code is a lengthy

task, and it is

repetitive.

Use Validation

controls in

ASP.NET

83

Validation Control Description

<asp:RequiredFieldValidator> Checks that the control it has to validate is not empty

when the form is submitted.

<asp:RangeValidator> Checks that the value of the associated control is within

a specified range. The value and the range can be

numerical—a date or a string.

<asp:CompareValidator> Checks that the value of the associated control matches

a specified comparison (less than, greater than, and so

on) against another constant value or control.

<asp:RegularExpressionValidator

>

Checks if the value of the control it has to validate

matches the specified regular expression.

<asp:CustomValidator> Allows you to specify any client-side JavaScript validation

routine and its server-side counterpart to perform your

own custom validation logic.

<asp:ValidationSummary> Shows a summary with the error messages for each

failed validator on the page (or in a pop-up message

box).

Page 22: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.5 INPUT VALIDATION CONTROLS

Most web controls contain a property named CausesValidation.

By default, it is set to False, except button control.

It is assumed that when you click a button that you want to

perform validation.

If you set the CausesValidation and the AutoPostBack property

to true at the same time for any control, validation will be

performed.

If the validation fails, the page will not postback to the server.

84

Page 23: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.5 INPUT VALIDATION CONTROLS

Validator Base Class Properties:

85

Member Description

ControlToValidate Indicates the input control to validate.

Display Indicates how the error message will be shown. If Static, the space required to show the message will be calculated

and added to the space layout in advance. If Dynamic, the page layout will dynamically change to show the error

string. Be aware that although the dynamic style could seem useful, if your layout is heavily based on table structures,

it could change quite a bit if multiple strings are dynamically added, and this could confuse the user.

EnableClientScript A Boolean property that specifies whether the client-side validation will take place. It is true by default.

Enabled A Boolean property that allows the user to enable or disable the validator. When the control is disabled, it does not

validate anything. You can set this property programmatically if you want to create a page that dynamically decides

what it should validate.

ErrorMessage Error string that will be shown in the errors summary by the Validation-Summary control, if present.

Text The error text that will be displayed in the validator control if the attached input control fails its validation.

IsValid This property is also usually read or set only from script code (or the code-behind class) to determine whether the

associated input control’s value is valid. This property can be checked on the server after a postback, but if the client-

side validation is active and supported by the client browser, the execution won’t get to the server if the value isn’t

valid. (In other words, you check this property just in case the client-side validation did not run.) Remember that you

can also read the Page.IsValid property to know in a single step if all the input controls are in a valid state. Page.IsValid

returns true only if all the contained controls are valid.

SetFocusOnError If true, when the user attempts to submit a page that has an invalid control, the browser switches focus to the input

control so the value can be easily corrected. (If false, the button or control that was clicked to post the page retains

focus.) This feature works for both client-side and server-side validation. If you have multiple validators with

SetFocusOnError set to true, and all the input controls are invalid, the first input control in the tab sequence gets focus.

ValidationGroup Allows you to group multiple validators into a logical group so that validation can be performed distinctly without

involving other groups. This is particularly useful if you have several distinct panels on a web page, each with its own

submit button.

Validate() This method revalidates the control and updates the IsValid property accordingly. The web page calls this method when

a page is posted back by a CausesValidation control. You can also call it programmatically (for example, if you

programmatically set the content of an input control and you want to check its validity).

Page 24: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.5 INPUT VALIDATION CONTROLS

RequiredField Validator:

Required value in a control.

Value in control must be different from InitialValue .

RangeValidator:

Input value must fall within specified range.

Set MinimumValue, MaximumValue and Type (Currency, Date, Double,

Integer, and String)

CompareValidator:

Compare input value with a fixed value or a value in another control.

Example: Confirm password

ValueToCompare (fixed value), ControlToCompare (control value)

Operator: Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan,

LessThanEqual, DataTypeCheck

86

Page 25: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.5 INPUT VALIDATION CONTROLS

RegularExpression Validator:

Validate text by matching against a pattern defined in a regular

expression.

Comes with predefined list of specific expressions.

Example: E-mail address

CustomValidator:

If none of the built-in validators meets your needs, then use

CustomValidator.

Create custom Client and Server side validation validation routines.

ValidationSummary:

No validation, instead displays summary of all validation errors in the

page.

Summary can be shown in JavaScript messagebox or on the page, or use

both display methods.

87

Page 26: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.5 INPUT VALIDATION CONTROLS

88

Page 27: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.5 INPUT VALIDATION CONTROLS

89

Page 28: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.5 INPUT VALIDATION CONTROLS

90

Page 29: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.5 RICH CONTROLS

Web controls that model complex user interface elements.

Rich controls can be programmed as a single object (defined

with a single control tag), but renders itself with a complex

sequence of HTML elements including JavaScript.

Calendar Control

91

Page 30: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.5 RICH CONTROLS

92

Page 31: Dynamic Web Programming BUILDING WEB …€¦ · Page Returns a reference to the page object that contains the control. Parent Returns a reference to the control’s parent, which

5.5 RICH CONTROLS

93