Вы находитесь на странице: 1из 15

MscIT – KSV Semester II -2012

Building Applications using Microsoft .Net Platform

Chapter 3 WebForms and Controls

Overview of ASP.NET and Web Forms

Microsoft® ASP.NET is the next generation technology for Web application development. It takes the best from Active Server Pages (ASP) as well as the rich services and features provided by the Common Language Runtime (CLR) and add many new features. The result is a robust, scalable, and fast Web development experience that will give you great flexibility with little coding.

Web Forms are the heart and soul of ASP.NET. Web Forms are the User Interface (UI) elements that give your Web applications their look and feel. Web Forms are similar to Windows Forms in that they provide properties, methods, and events for the controls that are placed onto them. However, these UI elements render themselves in the appropriate markup language required by the request, e.g. HTML. If you use Microsoft Visual Studio® .NET, you will also get the familiar drag-and-drop interface used to create your UI for your Web application.

Web Forms are made up of two components: the visual portion (the ASPX file), and the code behind the form, which resides in a separate class file.

behind the form, which resides in a separate class file. Figure 1. Web Forms are a

Figure 1. Web Forms are a part of ASP.NET

The Purpose of Web Forms

Web Forms and ASP.NET were created to overcome some of the limitations of ASP. These new strengths include:

Separation of HTML interface from application logic

A rich set of server-side controls that can detect the browser and send out appropriate markup

language such as HTML

Less code to write due to the data binding capabilities of the new server-side .NET controls

By Darshna Patel

MscIT – KSV Semester II -2012

Building Applications using Microsoft .Net Platform

Event-based programming model that is familiar to Microsoft Visual Basic® programmers

Compiled code and support for multiple languages, as opposed to ASP which was interpreted as

Microsoft Visual Basic Scripting (VBScript) or Microsoft Jscript®

Allows third parties to create controls that provide additional functionality

On the surface, Web Forms seem just like a workspace where you draw controls. In reality, they can do a whole lot more. But normally you will just place any of the various controls onto the Web Form to create your UI. The controls you use determine which properties, events, and methods you will get for each control. There are two types of controls that you can use to create your user interface: HTML controls and Web Form controls.

All server controls must appear within a <form> tag, and the <form> tag must contain the runat="server" attribute. The runat="server" attribute indicates that the form should be processed on the server.

The form is always submitted to the page itself. If you specify an action attribute, it is ignored. If you omit the method attribute, it will be set to method="post" by default. Also, if you do not specify the name and id attributes, they are automatically assigned by ASP.NET.

Note: An .aspx page can only contain ONE <form runat="server"> control!

If you select view source in an .aspx page containing a form with no name, method, action, or id attribute specified, you will see that ASP.NET has added these attributes to the form. It looks something like this:

<form name="_ctl0" method="post" action="page.aspx" id="_ctl0">

some code

</form>

Page Execution life Cycle

Stage

Page request

Start

Initialization

Description

The page request occurs before the page life cycle begins. When the page is requested by

a user, ASP.NET determines whether the page needs to be parsed and compiled

(therefore beginning the life of a page), or whether a cached version of the page can be

sent in response without running the page.

In the start stage, page properties such as Request and Response are set. At this stage,

the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property. During page initialization, controls on the page are available and each control's UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

Load During load, if the current request is a postback, control properties are loaded with

By Darshna Patel

MscIT – KSV Semester II -2012

Building Applications using Microsoft .Net Platform

Postback event handling

Rendering

Unload

information recovered from view state and control state. If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page. Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property. The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.

Life-Cycle Events

Within each stage of the life cycle of a page, the page raises events that you can handle to run your own code. For control events, you bind the event handler to the event, either declaratively using attributes such as onclick, or in code.

Pages also support automatic event wire-up, meaning that ASP.NET looks for methods with particular names and automatically runs those methods when certain events are raised. If the AutoEventWireup attribute of the @ Page directive is set to true, page events are automatically bound to methods that use the naming convention of Page_event, such as Page_Load and Page_Init. For more information on automatic event wire-up, see ASP.NET Web Server Control Event Model.

The following table lists the page life-cycle events that you will use most frequently. There are more events than those listed; however, they are not used for most page-processing scenarios. Instead, they are primarily used by server controls on the ASP.NET Web page to initialize and render themselves. If you want to write custom ASP.NET server controls, you need to understand more about these events.

Page Event

Typical Use

 

Raised after the start stage is complete and before the initialization stage begins.

Use this event for the following:

PreInit

Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.

Create or re-create dynamic controls.

Set a master page dynamically.

Set the Theme property dynamically.

Read or set profile property values.

By Darshna Patel

MscIT – KSV Semester II -2012

Building Applications using Microsoft .Net Platform

 

Note

If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.

Init

Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.

Use this event to read or initialize control properties.

InitComplete

Raised at the end of the page's initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.

Use this event to make changes to view state that you want to make sure are persisted after the next postback.

PreLoad

Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.

Load

The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.

Use the OnLoad event method to set properties in controls and to establish database connections.

 

Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.

Control events

Note In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.

 

Raised at the end of the event-handling stage.

LoadComplete

Use this event for tasks that require that all other controls on the page be loaded.

PreRender

Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)

The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls

By Darshna Patel

MscIT – KSV Semester II -2012

Building Applications using Microsoft .Net Platform

 

occurs after the PreRender event of the page.

Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.

PreRenderComplete

Raised after each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.

SaveStateComplete

Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.

 

This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup to send to the browser.

Render

If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.

A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.

 

Raised for each control and then for the page.

In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.

Unload

For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

Note During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

ViewState :

When a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted a form with a lot of information and the server comes back with an error. You will have to go back to the form

and correct the information. You click the back button, and what happens

CLEARED, and you will have to start all over again! The site did not maintain your ViewState.

ALL form values are

When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. How come? This is because ASP .NET maintains your ViewState. The ViewState indicates the

By Darshna Patel

MscIT – KSV Semester II -2012

Building Applications using Microsoft .Net Platform

status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a <form runat="server"> control. The source could look something like this:

<form name="_ctl0" method="post" action="page.aspx" id="_ctl0">

<input type="hidden" name="

value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" />

VIEWSTATE"

some code

</form>

Maintaining the ViewState is the default setting for ASP.NET Web Forms. If you want to NOT maintain the ViewState, include the directive <%@ Page EnableViewState="false" %> at the top of an .aspx page or add the attribute EnableViewState="false" to any control.

View state is the method that the ASP.NET page framework uses to preserve page and control values between round trips. When the HTML markup for the page is rendered, the current state of the page and values that must be retained during postback are serialized into base64-encoded strings. This information is then put into the view state hidden field or fields.

ViewState represents the state of a page when it was last processed on the web server. It holds the values of a control that has been dynamically changed.

How does ViewState work?

All server controls have a property called ViewState. If this is enabled, the ViewState for the control is also enabled. Where and how is ViewState stored? When the page is first created all controls are

serialized to the ViewState, which is rendered as a hidden form field named

field corresponds to the server side object known as the ViewState. ViewState for a page is stored as key- value pairs using the System.Web.UI.StateBag object. When a post back occurs, the page de-serializes the

ViewState and recreates all controls. The ViewState for the controls in a page is stored as base 64 encoded strings in name - value pairs. When a page is reloaded two methods pertaining to ViewState are called, namely the LoadViewState method and SaveViewState method. The following is the content of the

ViewState.

This hidden

ViewState

hidden field as generated for a page in my system.

<input type="hidden" name="

VIEWSTATE"

value="dNrATo45Tm5QzQ7Oz8AblWpxPjE9MMl0Aq765QnCmP2TQ==" />

Enabling and Disabling ViewState

By default, ViewState is enabled for all server controls. ViewState can be enabled and disabled in any of the following ways.

Page Level

Control Level

Application Level

Machine Level

By Darshna Patel

MscIT – KSV Semester II -2012

Building Applications using Microsoft .Net Platform

To enable or disable ViewState in the Page Level, use the following in the Page directive of the ASP.NET page.

<%@ Page EnableViewState ="False" %> or <%@ Page EnableViewState ="True" %>

To enable or disable ViewState at the Control Level, use the following:

<asp:TextBox id="txtCode" runat="server” EnableViewState="false" /> or <asp:TextBox id="txtCode" runat="server" EnableViewState="true" />

To enable or disable ViewState in the Application Level, use the following:

<pages enableViewState="false" /> or <pages enableViewState="true" />

To enable ViewState in the Machine Level, use the following:

<pages enableViewState="true" enableViewStateMac="true" or

<pages enableViewState="false"

/>

/>

Saving and Restoring Values to and from the ViewState

To add an ArrayList object to the ViewState use the following statements.

ArrayList obj = new ArrayList();

ViewState[

"ViewStateObject"

] = obj;

To retrieve the object later use:

obj = ViewState[

"ViewStateObject"

];

IsPostBack :

In ASP.Net, the Page Load is event is fired every time a page is loaded. This is true even if the page is loaded as part of a submit button click. You may need to identify if the page load event is called as part of a page submit or if it is a fresh page rendering. Because, in case of page submit, you may want to skip

several task

like

populating

the

data

again

etc.

By Darshna Patel

MscIT – KSV Semester II -2012

Building Applications using Microsoft .Net Platform

The IsPostBack property can be used to determine if the page is submitted to itself. When a form is posted (submitted) back to the same page that contains it, it's called a post back. ASP.NET provides a

property called IsPostBack that is TRUE when the page is being loaded as a result of a post back, and is

FALSE

otherwise.

We can check the value of this property and based on the value, we can populate the controls in the page. If the property is TRUE, that means it is a postback (submit) and no need to populate all the values again.

Examples : Page_Load()

{

If(page.IsPostBack==false)

}

//

New Request.

Let's look at the different types of controls that you can use in Web Forms and the ASP.NET Framework.

HTML Controls

HTML controls mimic the actual HTML elements that you would use if you were using Front Page or any other HTML editor to draw your UI. You can use standard HTML elements in Web Forms, too. For example, if you wanted to create a text box, you would write:

<input type="text" id=txtFirstName size=25>

If you are using Visual Studio .NET, you choose a TextField control from the HTML Toolbox tab and draw the control where you want it on the HTML page.

Any HTML element can be marked to also run as an HTML control when the Web Form is processed on the server by adding "runat=server" to the tag:

<input type="text" id=txtFirstName size=25 runat=server>

If you are using Visual Studio .NET, you can right-click the HTML element in Design View and select Run as Server Control from the context menu.

HTML controls allow you to handle server events associated with the tag (a button click, for example), and manipulate the HTML tag programmatically in the Web Form code. When the control is rendered to the browser, the tag is rendered just as it is saved in the Web Form, minus the "runat=server". This gives you precise control over the HTML that is sent to the browser.

By Darshna Patel

MscIT – KSV Semester II -2012

Building Applications using Microsoft .Net Platform

Table 1. HTML controls available in ASP.NET

Control

Description

 

Web Form Code Example

Button

A normal button that you can use to respond to Click events

<input type=button runat=server>

Reset Button

Resets

all

other

HTML

form

<input type=reset runat=server>

elements on

a

form

to

a default

value

Submit Button

Automatically POSTs the form data to the specified page listed in the Action= attribute in the FORM tag

<input type=submit runat=server>

Text Field

Gives the user an input area on an HTML form

<input type=text runat=server>

Text Area

Used

for

multi-line

input

on

an

<input type=textarea runat=server>

HTML form

 

File Field

Places a text field and a Browse button on a form and allows the user to select a file name from their local machine when the Browse button is clicked

<input type=file runat=server>

Password Field

An input area on an HTML form, although any characters typed into this field are displayed as asterisks

<input

type=password

runat=server>

CheckBox

Gives the user a check box that they can select or clear

<input type=checkbox runat=server>

Radio Button

Used two or more to a form, and allows the user to choose one of the controls

<input type=radio runat=server>

Table

Allows you to present information in a tabular format

<table runat=server></table>

Image

Displays an image on an HTML form

<img src="FileName" runat=server>

ListBox

Displays a list of items to the user. You can set the size from two or more to specify how many items you wish show. If there are more items than will fit within this limit, a scroll bar is automatically added to this control.

<select

size=2

runat=server

></select>

By Darshna Patel

MscIT – KSV Semester II -2012

Building Applications using Microsoft .Net Platform

Dropdown

Displays a list of items to the user, but only one item at a time will appear. The user can click a down arrow from the side of this control and a list of items will be displayed.

<select><option></option></select>

Horizontal Rule

Displays a horizontal line across the HTML page

<hr>

All of these controls write standard HTML into the Web Form. You may optionally assign an ID attribute to each control, allowing you to write client-side JavaScript code for any of the events that are common for this particular type of control. Below is a partial list of some of the more common client-side events.

Table 2. Common client-side events

Control

Description

OnBlur:

Control loses focus

OnChange:

Contents of the control are changed

OnClick:

Control is clicked on

OnFocus:

Control receives focus

OnMouseOver:

Mouse moves over this control

Web Form Controls

Web Form controls are created and run on the Server just like the HTML controls. After performing whatever operation they are designed to do, they render the appropriate HTML and send that HTML into the output stream. For example, a DropDownList control will allow you to bind to a data source, yet the output that is rendered is standard <SELECT> and <OPTION> tags when sent to a browser. However, the same DropDownList control might render WML if the target is a portable phone. That is why these controls do not necessarily map to any one markup language, but have the flexibility to target the appropriate markup language.

All Web Form controls inherit from a common base class, namely the System.Web.UI.WebControls class. This base class implements a set of common properties that all of these controls will have. Some of these common properties are:

BackColor

Enabled

Font

ForeColor

By Darshna Patel

MscIT – KSV Semester II -2012

Building Applications using Microsoft .Net Platform

Modifiers

TabIndex

Visible

Width

There are a few different categories of controls that are supplied by the Microsoft .NET Framework. Some controls have an almost one-to-one correspondence with their HTML counterparts. Some controls provide additional information when posted back to the server, and some controls allow you to display data in tabular or list-type format. Table 2 shows a list of Web Form server-side controls and the server- side events that you can respond to with each control.

Table 2. Server-side controls used in ASP.NET and Web Forms

 

Commonly

Used

Control

Description

 

Server-Side Events

Web Form Code Example

 

Label

Displays

text

on

None

<asp:Label

id=Label1

the

HTML page

runat="server">Label</asp:Label>

TextBox

Gives

the

user

an

TextChanged

<asp:TextBox

id=TextBox1

input

area

on

an

runat="server"></asp:TextBox>

HTML form

 

Button

A

normal

button

Click, Command

<asp:Button

id=Button1

runat="server"

control

used

to

Text="Button"></asp:Button>

respond

to

click

events

on

the

server.

You

are

allowed

to

pass

additional

 

information

 

by

setting

 

the

CommandName and CommandArgumen ts properties.

LinkButton

Like a button in that it posts back to a server, but the button looks like a hyperlink

Click, Command

<asp:LinkButton

id=LinkButton1

runat="server">LinkButton</asp:LinkBut

ton>

ImageButton

Can

display

a

Click

<asp:ImageButton

id=ImageButton1

graphical

 

image,

runat="server"></asp:ImageButton>

and

when

clicked,

By Darshna Patel

MscIT – KSV Semester II -2012

Building Applications using Microsoft .Net Platform

 

posts back

to

the

   

server

command

information

 

such

as

the

mouse

coordinates within

the

image,

when

clicked

 

Hyperlink

A normal hyperlink control that

None

<asp:HyperLink

id=HyperLink1

runat="server">HyperLink

responds to a click

</asp:HyperLink>

event

 

DropDownList

A

normal

SelectedIndexChang

<asp:DropDownList

id=DropDownList1

dropdown list control like the HTML control, but can be data bound to a data source

ed

runat="server"></asp:DropDownList>

ListBox

A

normal ListBox

SelectedIndexChang

<asp:ListBox

id=ListBox1

control like the HTML control, but can be data bound to a data source

ed

runat="server"></asp:ListBox>

DataGrid

Like a <TABLE> on steroids. You bind

CancelCommand,

<asp:DataGrid

id=DataGrid1

EditCommand,

runat="server"></asp:DataGrid>

a

data source to

DeleteCommand,

this control and it displays all of the

ItemCommand,

SelectedIndexChang

column

 

ed,

information. You can also perform paging, sorting, and formatting very easily with

PageIndexChanged,

SortCommand,

UpdateCommand,

ItemCreated,

ItemDataBound

this control.

 

DataList

Allows

you

to

CancelCommand,

<asp:DataList

id=DataList1

create

a

non-

EditCommand,

runat="server"></asp:DataList>

tabular

type

of

DeleteCommand,

format

for

data.

ItemCommand,

You

can

bind

the

SelectedIndexChang

data

to

template

ed,

items,

which

are

UpdateCommand,

like

bits

of

HTML

ItemCreated,

By Darshna Patel

MscIT – KSV Semester II -2012

Building Applications using Microsoft .Net Platform

 

put

together

in

a

ItemDataBound

 

specific repeating

format.

 

Repeater

Allows

you

to

ItemCommand,

<asp:Repeater

id=Repeater1

create

a

non-

ItemCreated,

runat="server"></asp:Repeater>

tabular

type

of

ItemDataBound

format

for

data.

You

can

bind

the

data

to

template

items,

which

are

like

bits

of

HTML

put

together

in

a

specific

repeating

format.

CheckBox

Very similar to the normal HTML control that displays a check box for the user to check or uncheck

CheckChanged

<asp:CheckBox

id=CheckBox1

runat="server"></asp:CheckBox>

CheckBoxList

Displays a group of check boxes that all work together

SelectedIndexChang

<asp:CheckBoxList

id=CheckBoxList1

ed

runat="server"></asp:CheckBoxList>

RadioButton

Very similar to the normal HTML control that displays a button for the user to check or uncheck

CheckChanged

<asp:RadioButton

id=RadioButton1

runat="server"></asp:RadioButton>

RadioButtonLi

Displays a group of

SelectedIndexChang

<asp:RadioButtonList

st

radio

 

button

ed

id=RadioButtonList1

controls that all work together

runat="server"></asp:RadioButtonList>

Image

Very similar to the normal HTML control that displays an image within the page

None

<asp:Image

id=Image1

runat="server"></asp:Image>

Panel

Used

to

group

None

<asp:Panel

id=Panel1

other controls

 

runat="server">Panel</asp:Panel>

By Darshna Patel

MscIT – KSV Semester II -2012

Building Applications using Microsoft .Net Platform

PlaceHolder

Acts as a location

None

<asp:PlaceHolder

id="PlaceHolder1"

where

you

can

runat="server"></asp:PlaceHolder>

dynamically

add

other server-side

controls at

run

time

Calendar

Creates an HTML version of a calendar. You can set the default

SelectionChanged, VisibleMonthChange d, DayRender

<asp:Calendar

id=Calendar1

runat="server"></asp:Calendar>

date,

move

 

forward

and

backward through the calendar, etc.

AdRotator

Allows you to specify a list of ads to display. Each time the user re- displays the page, the display rotates through the series of ads.

AdCreated

<asp:AdRotator

id=AdRotator1

runat="server"></asp:AdRotator>

Table

Very similar to the normal HTML control

None

<asp:Table

id=Table1

runat="server"></asp:Table>

XML

Used to display XML documents within the HTML, It can also be used to perform an XSLT transform prior to displaying the XML.

None

<asp:Xml

id="Xml1"

runat="server"></asp:Xml>

Literal

Like a label in that it displays a literal, but allows you to create new literals at runtime and place them into this control

None

<asp:Literal

id="Literal1"

runat="server"></asp:Literal>

By Darshna Patel

MscIT – KSV Semester II -2012

Building Applications using Microsoft .Net Platform

All of these controls change their output based on the type of browser detected for the user. If the user's browser is IE, a richer look and feel can be generated using some DHTML extensions. If a down-level browser is detected (something other than IE), normal HTML 3.2 standard is sent back to the user's browser.

Chapter 3 Webform and Webserver Controls (QuestionBank).

1)What is winform? Explain its basic properties. (4 marks). 2) Explain Advantages of Asp.Net over Classical ASP. 3) What are Web Forms ? Explain in brief how does the web forms work. (4 marks). 4) Explain Page Life cycle (4 Marks) 5) Explain the ASP.Net architecture in brief. Which are the four most commonly used file extensions for .Net files, explain then in brief. (5 marks). 6) What are HTML Server controls ? Explain them in brief. (4 marks). 7) What are Web Server controls ? Explain them in brief. (4 marks). 8) What is Viewstate ? 9) Explain Page.IsPostBack Property. 10) What is AutoEventMarkup.

By Darshna Patel