Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Net
Introducing ASP .NET – Creating and deploying ASP .NET applications – Web forms –
Web controls – working with events – Rich web controls – Custom web controls –
Validation controls – Debugging ASP .NET pages.
• Before .NET came into the game, tools to support Internet application
development were sort of pasted on top of the operating system and usually
produced not too clean-cut solutions.
• Active Server Pages (ASP), introduced by Microsoft around 1995, consisted of
HTML mixed with server-side script, and its goal was to dynamically build
HTML from the script. Although useful for web application development, it relied
on interpreted scripting. The business logic (script) was mixed with the
presentation logic (HTML) and the script was type-less, which reduced its
robustness.
• ASP pages offered very poor modularity. Also, a lot of redundant scripting code
had to be done for each ASP; one could not factor and reuse the repeating
boilerplate code. More importantly, ASP, although convenient for Internet apps,
was at the same time a step backwards into interpreted non type-safe, non-
structured and non object-oriented code.
• The design, debugging and maintenance of the resulting spaghetti code were
unpleasant to any developer used to traditional applications.
• Microsoft pushed forward a very attractive architecture called Windows DNA,
based on COM (Component Object Model – the Microsoft binary model for
pre-.NET components) that separates the development into 3 tiers: ASP in the
presentation layer, business objects in the middle layer, and relational data store
and engine in bottom layer. Its main weaknesses were related to:
Understanding COM was never easy and neither programming it; although
some languages like VB did make it much easier to work with than VC++,
albeit with some loss in versatility
Deployment of DNA applications could become a nightmare, because of the
many potential problems that can arise from version-conflicts.
The only real problem with this effort was that architecture without a
corresponding framework and tools to support it is truly very hard to achieve,
and this was the case before .NET arrived at the scene.
2. Introducing ASP.Net
• ASP.Net enables to access information from the data sources, such as back-end
databases and text files that are stored on a web server or a computer that is
accessible to a web server.
• ASP.Net enables to use a set of programming code called templates to create
HTML documents. The advantage of using templates is that you can dynamically
insert content retrieved from data sources, such as back-end databases and text
files, into an HTML document before the HTML document is displayed to users.
Therefore, the information need not be changed manually as and when the content
retrieved from data source change.
• ASP.Net also enables you to separate HTML design from the data retrieval
mechanism. Therefore, changing the HTML design does not affect the program
that retrieve data from the databases. Similarly, server-side scripting ensures that
changing data sources does not require a change in HTML documents.
Features of ASP.Net
In addition to hiding script commands, ASP.Net has the following advanced features that
help develop robust web applications.
• Compiled code: Code written in ASP.Net is compiled and not interpreted. This
makes ASP.Net applications faster to execute that other server-side scripts that are
interpreted, such as scripts written in a previous version of ASP.
When you request a page for the first time, the run time compiles the code and the
page itself, and keeps a cached copy of the compiled result. When you request the
page the second time, the cached copy is used. This results in greatly increased
performance because, after the first request, the code can run from the much faster
compiled version and the content on the page does not need to be parsed again.
• Enriched Tool Support: The ASP.Net framework is provided with a rich toolbox
and designer in VS.Net IDE. Some of the powerful features are WYSYWIG
controls and automatic deployment.
• Power and Flexibility: ASP.Net applications are based on CLR. Therefore the
power and flexibility of .Net platform is available to ASP.Net application
developers. ASP.Net applications enable you to ensure that the .Net framework
class library, messaging, and data access solutions are seamlessly accessible over
the web.
• Multiple Language Support: It provides a true language-neutral execution
framework for the web application. ASP.Net is also language independent.
Therefore, you can choose any .Net language to develop you application.
• Simplicity: ASP.Net enables you to build user interfaces that separate application
logic from presentation content. In addition, CLR simplifies application
development by using managed code services, such as automatic reference
counting and garbage collection. Therefore, ASP.Net makes it easy to perform
common tasks ranging from form submission and client authentication to site
configuration and deployment.
• Manageability: ASP.Net enables you to manage Web applications by storing the
configuration information in an XML file. You can open the XML file in the
VS.Net IDE.
• Scalability: ASP.Net has been designed with scalability in mind. It has features
that help improve performance in a multiprocessor environment. A session-state
can be maintained in a separate process on a separate machine or database,
allowing for cross-server sessions.
• Security: ASP.Net provides a number of options for implementing security and
restricting user access to a web application. All these options are configured
within the configuration files. One can create form based authentication, and
create login forms.
• Classes and Namespaces: ASP.Net includes a range of useful classes and
namespaces. Namespaces are like class libraries and can make writing web
applications easier. Some of the classes included with ASP.Net are HtmlAnchor,
HtmlControl, and HtmlForm, which are included within the
System.Web.UI.HtmlControls.
• Server Controls: ASP.Net provides several server controls that simplify the tazsk
of creating pages. These server controls encapsulate common tasks that range
from displaying calendars and tables to validating user input. They automatically
maintain their selection states and expose properties, methods, and events for
server-side code, there by providing a clean programming model.
• Web Services: A web service is an application delivered as a service that can be
integrated with other web services by using Internet Standards. ASP.Net allows to
create and use web services.
For example, a company can assemble an online store by using the Microsoft
Passport service to authenticate users, a third-party personalization service to
adapt Web pages to each user’s preferences, a credit-card processing service, a
sales tax service, and package-tracking services from each shipping company, and
an in-house catalog service that connects to the company’s internal inventory
management applications.
Web services provide the building blocks for constructing distributed webbased
applications. ASP.Net files have an .aspx extension and web services have an
.asmx extension.
• Cookie-less Sessions: ASP.Net enables to use session state even with browsers
that have cookie supported disabled. Cookie-less sessions use Uniform Resource
Locators as opposed to cookies, to pass the sessionID to an ASP.Net page. A
cookie-less session involves encoding data into a URL, which is done
automatically by the browser.
• Easy configuration and deployment: Configuration and deployment are now
easier with the use of human-readable configuration files and DLLs that do not
need to recognized.
In ASP.Net, all the configuration details for all web applications are kept in
human readable files named web.config. The standard format for the
configuration files is XML, and each application inherits the settings in the
default web.config file.
With .Net, all files that a web site needs are located under the site’s root folder.
DLLs are in the /bin folder, and the web.config is in the root folder. To deploy a
web site, all you need to do is copy the site’s root folder by using file copy
commands, Microsoft front page server extensions, or File transfer protocols.
ASP.NET is the answer to ASPs weaknesses. Most of its innovations are aimed at the
Web developer who doesn’t know much beyond HTML.
ASP.NET introduces server controls, which means we can use HTML-like tags to
accomplish something that in ASP required both HTML and scripting.
In ASP if you wanted a control to keep state between web pages when someone
refreshed a page, you’d also have to write script code. Not anymore; ASP.NET
may automatically keep track of state for us.
In ASP one could use procedures and functions, but without calling this via
events, you were still confined to a sequential execution order. Therefore, many
developers, out of complexity or ignorance, did not give much use to structured
programming; not to mention object-oriented programming which was simply not
available.
With ASP.NET two concepts are introduced. Code behind, comes into play when
an ASP.NET page is compiled, producing a base class from which the page
inherits. Therefore, ASP.NET pages are now objects.
The other concept is that of user controls (custom controls derived from .NET
provided server side Web controls). Just like we could create ActiveX controls for
the user interface for traditional Windows applications, we now have the same
capability but for use in the user interface of Internet applications (i.e. browsers).
Additionally the page can make transparent use of any .NET or COM component
and it can contain methods, properties, events, attributes, etc, just like any other
object. Since these pages are now classes, it should come as no surprise that they
can be compiled (the first time a page is run) and that we can use any .NET
language to program them.
Separating Presentation from Code: The idea of code behind, allows us to
separate the presentation aspect written basically in HTML and tags representing
Web controls from the class that represents the page. Both are tightly
interconnected by a special tag in the .aspx file (not .asp anymore). For example,
the following is the first line of an .aspx file:
<%@ Page language="c#" Codebehind="default.aspx.cs"
AutoEventWireup="false" Inherits="MyFirstWebApplication.DefaultWebForm"
trace="true" %>
3. Set up the development environment of ASP.Net
ASP.Net is based on the CLR, class libraries, and other tools integrated with the
Microsoft.Net framework. Therefore, to develop and run the ASP.Net applications, it is
required to install the .Net framework. The .Net framework is available in two forms:
The .Net framework SDK or VS.Net is installed on a machine that has one of the
following OS:Windows 2000, Windows NT 4.0, Windows Me, Windows 98, Windows
XP professional.
Installation of .Net framework SDK is very simple. Just run the setup program and follow
the onscreen instructions. However, the development machine must have IE5.5 or higher
available before the installation. Otherwise, you will be prompted to download it before
you install the .Net framework SDK.
Note: To develop any web application, you need Internet Information Server (IIS)
configured on either the development machine or another machine on network. The .Net
framework must be installed on the machine on which IIS is configured.
In the case of Windows 2000 Server, the IIS server is automatically installed. For
ASP.Net database applications, one must install SQL Server 7.0.
To crate ASP.Net applications by just installing the .Net framework SDK and configuring
an IIS server. In this case, text editor such as, notepad is used to write the code.
(ii) VS.Net
When setup program is run from VS.Net CD1, a dialog box appears that prompts for the
following three options:
Windows component update, install visual studio.net, check for service releases
The VS.Net start page is displayed. The VS.Net window contains the solution explorer
window. The options available on the start page:
ASP.Net web pages consist of HTML text and the code. The HTML text and the code
can be separated in two different files. The code is written in VB or C#. This separate file
is called the code behind file.
At the top of the page, specify @ Page directive to define page specific attributes, such as
language. Example
Deployment is the process of distributing the finished applications (without the source
code) to be installed on other computers. In VS.Net the deployment mechanism is the
same irrespective of the programming language and tools used to create applications. The
steps are:
Step 1: Open the web application project.
Step 2: Select File-> Add Project -> New project dialog box
Step 3: From Project types pane, select setup and deployment projects. From the
Template pane, select Web Setup Project
Step 4: Change the default name of the project
Step 5: Click Ok to complete the process. The project is added to the solution explorer
window. Also, a File System editor window appears to the left. The editor
window has two panes. The left pane displays different items. The right pane
displays the content of the item selected in the left pane.
Step 6: Select Web Application Folder in the left pane of the File System editor window.
Then, from the Action Menu, select Add-> Project Output to open the Add
Project Output Group Dialog box.
Step 7: Verify the given project is selected in the Project drop-down list. Then select
primary output and content files from the list.
Step 8: Click Ok. The output files and content files of the given project are added to the
solution.
Step 9: Select Web Application Folder in the File system editor and select properties
window from the view menu to open the properties window.
Step 10: Set the virtual directory property to a folder that would be the virtual directory
on the target computer where you want to install the application. By default, this
property is set to name of Web Setup project that is added by user. Set the
property to DeployedApplication.
Note: Folder name is new folder name and should not already exist on target
machine.
Step 11: In the same properties window of the web application folder, set the
DefaultDocument property to WebForm1.aspx. This property is used to set the
Default web forms page for the application.
Step 12: Build the solution by selecting Build Solution from the Build Menu.
Step 13: After the solution is built successfully, a SampleVBDeploy.msi file is created in
the Debug directory of the web setup project. The default path is
Step 14: Copy the SampleVBDeploy.msi file to the Web server computer
C:\inetpub\wwwroot
Step 15: Double click the SampleVBDeploy.msi file on the target computer to run the
installer.
5. ASP.Net in .Net framework: Its application elements
ASP.Net, which is the .Net version of ASP, is built on Microsoft .Net framework.
Microsoft introduced the .Net framework to help developers create globally distributed
software with Internet functionality and interoperability. The following figure illustrates
the elements of an ASP.Net application and how the elements fit in the broader context of
.Net framework.
ASP.net page
Framework
State Management
Application State
As shown in the figure, the elements of ASP.Net application include web forms,
configuration files and XML web service files. Web forms enable to include user
interfaces, such as text box, list box controls and application logic of web applications,
and configuration files enables to store the configuration settings of ASP.Net application.
The elements of ASP.Net application also include web services to provide a mechanism
for programs to communicate over the Internet. Web forms and the state management
features of ASP.Net make the ASP.Net page framework. There are also a number of
runtime services available in ASP.Net. The ASP.Net runtime services include session and
application state management, web security, and caching mechanism of ASP.Net
applications. The runtime services of ASP.Net interact with .Net framework base
classes. .Net framework base classes in turn interact with common language runtime
(CLR) to provide a robust web-based development environment.
6. Working of an ASP.Net application
The following figure describes how an IIS server processes the request for an ASP.Net
file.
<HTML> <HTML>
<Head> <Head>
<Title> Mypage </Title> <Title> Mypage </Title>
</Head> </Head>
<Body> <Body>
<H1> welcome </H1> <H1> welcome </H1>
<Embedded ASP.Net commands you are the first person.
and variables congrats
runat=server> welcome
</Body> </Body>
</HTML> </HTML>
A web server generates and sends only the HTML output to the client. Therefore, it helps
in hiding the code of the ASP.Net file from users accessing an ASP.Net web page.
o
ie u Parser Compiler
t
p
u
t Assembly cache
c Assembly IL
a Memory
c
h AssemblyIL
e Execute
HTTPRuntime
Client Server
Parser: The parser checks and interprets the contents of the aspx page and passes the page
to a compiler
Compiler: The run-time compiler is responsible for compiling the contents of the page
into an intermediate language
Assembly cache: Each machine on which Microsoft .Net framework is installed has
machine-wide code cache called the assembly cache. One of the functions of the
assembly cache is to hold the native code versions of pages that have been pre-compiled.
Memory: Some times that are expensive to construct can be built once and used for a
period of time before they are considered as invalid. These items are stored in memory
where they can be efficiently retrieved without incurring the cost of being reconstructed.
Output cache: The output cache is a cache for entire pages, including their objects and
data. After a page is built, it can be placed in the output cache. If a user makes another
request for the page, the request is returned from the output cache.
Directives, Code declaration blocks, Code render blocks, Server-side comments, and
Serverside include directives
(i) Directives:
A directive specifies how an ASP.Net page is compiled. The beginning of a directive
is marked with the characters <% @ and the end of the directive is marked with the
characters %>. The most frequently used directives are Page directive and Import
directives.
Page directives are used to specify the default programming language of a page.
Example: <%@ Page Language=”C#” %>
The Import directive is used to import additional namespace to a web application. For
example, to send an email message from ASP.Net page, you need to use Send method
of SmtpMail class. SmtpMail class is included in the System.Web.Mail namespace
which is not imported to a web application by default. To explicitly import the
namespace, the import directive as shown below:
You can application logic in either a code-behind file or the .aspx file of a web
application. If you want to add the application logic in the .aspx file, you need to
write application logic in a code declaration block. A code declaration block contains
the application logic of an ASP.Net page and the global variable declarations,
subroutines, and functions. The <Script Runat=”Server”> tag accepts two attributes.
The first attribute, Language, enables you to specify the language that is to be used
within the <Script> tag. The second attribute, SRC, is an optional attribute, which
enables you to specify an external file that contains the code block. You specify these
attributes in the HTML mode of .aspx files as shown below:
If you want to execute code within the HTML content of an ASP.Net page, you need
to use code render blocks. There are two types of code render blocks: Inline code and
Inline expressions. Inline code can execute a statement or a series of statements.
Inline code begins with the characters <% and ends with %>. Inline expressions
display the value of a variable or a method.
Inline expressions begin with the characters <%= and end with %>
<form runat=”Server”>
<% str=”Hello SRMIST”; %>
The value of str is:
<%=str%>
</form>
If you want to include an external file in an ASP.Net applications, you need to use server-
side Include directives. If the file is loaded in the same directory or in a subdirectory of
the directory in which the ASP.Net application is stored you need to use Include
directives:
You can also include the file by supplying the full virtual path. For example, if you have
a subdirectory named My_dir under wwwroot directory, you can include the file by using
the include directive:
ASP.Net provides two types of programming models: Web Forms, Web Services
Web Forms enable to create user interface for web applications. You use server controls
to design the user interface of web applications and then write code, which will be
executed at the server-side, to handle events triggered by these controls.
Web services enable you to remotely access certain functionality at the server side. These
services enable the exchange of data in a client-to-server environment over the web by
using SOAP. To enable this data exchange, web services use standards such as http and
xml messaging.
9. ASP.Net Web Forms
The ASP.Net web forms technology is used to create programmable web pages that are
dynamic, fast and interactive. Creation of web forms by using ASP.Net has following
advantages:
In ASP.Net web forms consist of a user interface and application logic that is applied to
the components of user interfaces.
A user interface consists of static HTML or XML elements, and ASP.Net server controls.
When you create a web application, HTML or XML elements and server controls are
saved in a file with a .aspx extension. This file is called a page file.
Application logic consists of code that is applied to the user interface elements of a web
form page. You can use any of .Net programming languages, such as VB.Net or C#, to
write the logic for a web page.
You design the user interface of a web page by using controls called ASP.Net server
controls. Server controls are different from usual windows controls because they work
within the ASP.Net framework. As soon as the client requests a web page, ASP.Net
converts these controls into HTML elements, which are displayed in the browser. These
controls support raising of events on user interaction. For example, if a user clicks a
button control, an event click is raised for the button on the client computer. However,
the browser does not process the event. Instead, the browser raises a postback event so
that the web server is alerted about the click event being raised. When the postback event
is raised by the browser for the occurrence of the click event of the button, the event
handler written for the click event is processed on the web server and the output is sent to
the client computer. The following figure illustrates handling of event raised for sever
controls.
A web browser displays Sample.aspx file that has a text box to enter username and
passwork and a button to submit.
As soon as the click event gets fired, the web broser sends postback event to alert the
webserver about the click event being raised.
The web server executes the event-handler for the click event of the submit button and
the welcome text for user is set
The web page with the processed output is sent back by web server
Output
In ASP.Net, each server control is an instance of a particular class. For example, when
you a add a button control to a web page, you accurately create an instance of Button
class. The base class of all server controls is the Control class that resides in the
System.Web.UI namespace. The hierarchy of sever controls in ASP.Net is depicted:
System.Object
System.Web.UI
System.Web.UI.Control
System.Web.UI.WebControls System.Web.UI.HTMLControls
PlaceHolder
Repeater
XML
System.Web.UI.WebControls
System.Web.UI.HTMLControls:
HtmlAnchor, HtmlButton, HtmlForm, HtmlGenericControl, HtmlTable
HtmlInoutCheckBox, HtmlTableCell, HtmlTableRow
ASP.Net HTML controls are server-side replicas of standard HTML tags and are
executed by aspnet_isapi.dll. The HTML tags are converted into HTML controls by using
attributes such as ID and RUNAT. After an HTML tag is converted into an HTML
control, the tag becomes a server-side object with properties, methods, collections and
events.
It is important to remember that HTML controls are included in ASP.Net for backward
compatibility. You will use HTML controls when you need to migrate an existing ASP
application to ASP.Net platform. To crate HtmlInputText control, you need to enter the
following line of code in a web form:
The HTML Server controls can also be included through HTML Tab in the toolbox.
(ii) ASP.Net Web controls
ASP.Net web controls include traditional form controls, such as buttons and text boxes.
They also include controls that provide functionality, such as displaying data in a grid
and selecting dates. The web controls exist in System.Web.UI.WebControls namespace
and are derived from the WebControl base class. A web control is always closed with a
trailing forward slash (/). The web controls with description:
One can decide to use HTML controls or web controls based on the requirements and
functionality of each server controls:
For example, you can use validation controls to check whether a user has entered a
password, whether the entered password contains a minimum of four characters and a
maximum of twenty characters and whether the entered password is combination of
letters and numbers.
Some of the validation controls are Compare Validator, Custom Validator, Range
Validator, RegularField Validator, RequiredField Validator and Validation Summary.
Custom controls are compiled software components that you can create to share the same
customized controls among a number of ASP.Net applications. You can share custom
controls without having to add a separate copy of the control in each ASP.Net
applications. You can crate a custom control by using a base control class, such as
WebControl class. Custom controls encapsulate user interface and the application logic
that is applied to the user interface into reusable packages. After you crate a custom
control, you can add it to the Toolbox. When you create a custom control, you install a
single copy of custom control and share it between applications. To access custom
control, you need to place the .dll file of custom control in the bin directory of the web
application that will use it. You also need to register it.
User controls
User controls are ASP.Net pages that are converted into controls. If you want to create a
server control that encapsulates the user interface of an existing web page, you can save
the page as a user control. User controls enable you to easily reuse the same content and
application logic in multiple ASP.Net pages. For example, you can create a company
logo once and save it as a user control. You can then use the same user control in
multiple web pages. The advantages of using user controls is that you can easily update
the content if required. For example, if the company logo changes, you need to change it
only in the file that contains the user control. To build a user control, you need to save the
web page with .ascx extension.
It is important to remember that you must register a user control in a web page before you
start using it:
<%@ Register TagPrefix=”ABC” TagName=”Header” Src=”Mypage.ascx” %>
TagPrefix is an alias to associate with the namespace of user control. Tagname is an alias
to associate with the class of user control. Src is the virtual path of the file containing user
control.
Composite controls: A composite control is a type of custom control that you can create
in an ASP.Net web applications. Composite controls are compiled controls that combine
the functionality of two or more existing controls
In addition to the custom controls, you can perform the following actions with controls:
Extend the functionality of existing web form controls to meet the requirements
Develop a custom control by inheriting directly from one of the control base
classes.
.
10. Some of the web controls
It is used to obtain information such as text, numbers, and dates for single line, password
or multiline data. The properties of text box control determine its appearance:
Checkboxes provide independent choices or options that you can select. CheckBoxList
control is a collection of several check boxes. After you add the checkboxlist control,
you need to add a list of items to it. You can add items to a check box by performing
the following steps:
Step 1: click the ellipses button for the items property of checkboxlist control
Step 2: In the ListItem collection editor dialog box, click the Add button. A new item is
created and its properties are displayed on the right side of dialog box.
Step 3: Verify that the item is selected in the Members list, and then set the properties
of the item. Each item is a separate object and has following properties:
Text: represents the text to be displayed for item in the list
Value: represents the value associated with the item without displaying it.
Selected: a Boolean value that indicates whether or not an item selected
Dim x as integer
X = CheckBoxList1.SelectedIndex()
Radio buttons provide a set of choices or options from that you can select.
RadioButtonList control is a collection of radio buttons. Usually, you use radio buttons
in a group. A group of radio buttons provides a set of mutually exclusive options. You
can select only one radio button in a group. You can group a set of radio buttons in two
ways:
Place a set of radiobutton controls in page and assign them manually to a group.
To do so, you can use the GroupName property
Place a RadiobuttonList control in a page. The radio button in the control are
automatically grouped. After you add a RadioButtonList control, you need to add
individual radio buttons. You can do so by using Items propery.
ListBox control is a list of predefined items and allows user to select one or more items
from the list. The ListBox control is a collection of list items. The individual list items
can be added used the Items property. Some of the properties are:
The DropDownList control allows user to select an item from a set of predefined items,
where each item is a separate object with its own properties, such as Text, Value and
Selected. You can select only one item at a time and the list of items remains hidden until
a user clicks the drop-down list button. Some of the properties are:
The HyperLink Control creates links in a web page and allows users to navigate from
one page to another in an application. You can use text or an image to act as a link in a
HyperLink control. When users click of the control, the target page opens. Some of the
properties:
A table is used to display information in a tabular format. You can add a table in Web
Forms page by using the Table control. This control can display information statically
by setting rows and columns at design time. In addition, you can program the Table
control to display information dynamically at run time. Some of the properties:
The Image control allows user to display images in a web forms page and manage them
at design or run time. Some of the properties are:
ImageUrl: used to represent the URL of the image to be displayed in the control
ImageAlign: used to represent the alignment of an image with respect to the
surrounding text.
Alternate Text: used to specify the alternate text in the image control when the
Image is unavailable. Browsers that support the ToolTips feature
Display the text as ToolTip.
The button control in web forms page is used to submit the page to the server. You can
create three types of server control buttons:
Text: Button and LinkButton: used to set the text to be displayed on the button
Enabled:Button, LinkButton and ImageButton: Whether or not the button is
available at run time.
ImageUrl: ImageButton: represents URL of the image to be displayed
AlternateText:ImageButton:represents the text that is displayed as a tooltip or
When the image cannot be loaded.
When users interact with different web controls on a page, events are raised. It can be
raised either on client or server, but are always handled on server.
Round Trips: Most web pages require processing on the server. The type of dynamic
functionality is accomplished by handling server control events. Whenever a user
interaction requires some kind of processing on the server, the web forms page is
submitted to the server, processed, and then returned to the browser. This sequence is
called a round trip.
Browser (.aspx) Server
(.aspx.vb or .aspx.cs)
Find Item
Application Code
Submit
Find Item
10 items found
Submit
Most of the user interactions with the server controls result in round trips. Because a
round trip involves sending the web forms page to the server and then displaying the
processed form in the browser, the server control events affect the response time in the
form. Therefore the number of events available in web forms server controls is limited,
usually to click events. The events that occur quite often, such as the OnMouseOver
event, are not supported by server controls. The events associated with different
ASP.Net server controls:
TextBox control: TextChanged Event: occurs when the content of text box is changed
Button, LinkButton, and ImageButton: Click: Occurs when you click the button. This
event causes the form to be submitted to the server.
By default, only click event of the Button, LinkButton and ImageButton server controls
causes the form to be submitted to the server for processing – the form is said to be
posted back to the server. The Change events associated with other controls are
captured and cached and do not cause the form to be submitted immediately. When the
form is posted back (as a result of button click), all the pending events are raised and
processed. No particular sequence exists for processing these change events, such as
TextChanged and CheckChanged on the server. The Click event is processed only after
all the change events are processed.
You can set the change events of server controls to result in the form post back to the
server. To do so, modify the AutoPostBack property to True.
Event Handlers:
When the events are raised, you need to handle them for processing. The procedures
that are executed when an event occurs are called event handlers. The event handler is
associated with the corresponding event by using WithEvents and Handles keywords.
The WithEvents keyword is used to declare the control generating an event. The
Handles keyword is used to associate the event handler with the event, which is raised
by the control.
Event Handlers are automatically created when you doubleclick the control in design
mode. For example when the Buttoncontrol Button1 is doubleclicked the code in the
event handler is:
………
End Sub
The procedure Button1_Click is the event handler for Click event of button. The handles
keyword associated the event with event handler. The procedure takes two arguments.
The first argument contains the event sender that can generate events. The second
argument contains the data.
Consider once the login user id and password is entered and pressed button1, a new web
form page is opened to display welcome message.
Lable1.Text = Request.QueryString(“strTextValue”)
5. To provide the reset functionality code associated with ReSet button is
UserName.Text=””
Email.Text=””
USStateList.ClearSelection()
The web form page is posted back to the server only when the server control buttons are
clicked. After the page is posted to the server, it is processed there. To respond to a
button event
• Write an event handler for click event of button
• Write event handler for load event of web form page. The load event is
generated when the form is loaded from the server to the browser. Use
IsPostBack property in the load event to determine whether the page has
been processed for first time or by a button click.
Whenever the web page is processed at the server, the page is created from scratch. In
traditional web applications, the server discards the page information after processing and
sending the page to the browser. Because the page information is preserved on the server,
the web pages are called stateless. However, the web forms framework works around this
limitation and can save the state information of the form and its controls. To implement
the following options are provide:
• The View State: The framework automatically saves the state of the page and its
current properties, and the state of the server controls and their base properties,
with each round trip.
• The StateBags: Every page has a state bag that stores values to be restored in the
next round trip.
The framework automatically stores and restores page information with each round trip.
The view state contains the state of all controls on page between requests sent to server.
The state information is stored as hidden form field as name-value pairs in the
System.Web.UI.StateBagObject. To view those values View Source in the browser. By
default viewstate is enabled for all server controls, but you can set
<%@ Page EnableViewState=”false” %>
ASP.Net provides controls that can be rendering of controls on server side. This allows
server-side processing, and thus provides dynamic web pages resulting in a rich and
improved user experience. Some of the Rich Web controls are
AdRotator control is sued to display flashing banner advertisements in web pages. The
controls is capable of displaying advertisements randomly. Some of the properties,
events, and methods of AdRotator control is as follows:
Property:
AdvertisementFile: used to set the path to XML file that contains list of banner
advertisements to display
KeyWordFilter: used to specify filter criteria based on which advertisements of
specific categories will be displayed in a web page
Target: used to specify the name of browser window that will display the contents of
linked web page when the AdRotator control is clicked. This parameter can also take
any of the HTML frame-related keywords.
Event:
AdCreated: This event is raised after an advertisement is retrieved from the
advertisement file and before the banner advertisement is rendered in a web page
Methods:
OnAdCreated: This method is used to raise the AdCreated event
Sample Code:
<Advertisements>
<Ad>
<ImageUrl>
Saturn.gif
</ImageUrl>
<NavigateUrl>
http://www.saturnrings.com/
</NavigateUrl>
<AlternateText>
Saturn Rings website
</AtlernateText>
<Impressions>
1
</Impressions>
<Keyword>
Saturn
</Keyword>
</Ad>
<Ad>
<ImageUrl>
Moon.gif
</ImageUrl>
<NavigateUrl>
http://www.moon.com/
</NavigateUrl>
<AlternateText>
Moon explores website
</AtlernateText>
<Impressions>
1
</Impressions>
<Keyword>
Moon
</Keyword>
</Ad>
</Advertisements>
The calendar control is used to display a one-month calendar. Users can use this control
to view dates or select a specific day, week or month. Calendar is one of the rich web
controls available in ASP.Net. Some of the properties, events and methods of Calendar
controls are:
Properties:
DayNameFormat: used to specify the name format of days of a week
FirstDayOfWeek: used to specify the day of the week to display in the first column of
calendar control
SelectedDate: used to represent the date selected in a calendar control
SelectionMode: used to specify whether a user can select a day, a week or a month.
Default value is Day.
VisibleDate: used to specify the month to be displayed in a Calendar control. It is
updated after the visibleMonthChanged event is raised
TodaysDate: used to specify a Date Time value that sets the current date of calendar
Events:
Methods:
Sample Code:
Properties:
AutoPostBack: used to specify whether or not the control posts back to the server on
each client request.
AutoSelect: used to specify whether or not a tree node can be selected by pointing the
mouse to the node without clicking the node.
ImageURL: used to specify the location of an image that is to be displayed to
represent a node
Events:
Collapse: raised when a user click a tree node to collapse it
Expand: raised when a user clicks a tree node to expand it
The toolbar control is used to render a toolbar in client browser. It is a container for one
of the following controls.
Properties:
AutoPostBack: used to specify whether or not the control posts back to server
after each client request.
DefaultStyle: used to specify a default style for the toolbar
Events:
ButtonClick:raised when a user clicks to a toolbar button
CheckChange:event is raised when the state of a ToolbarCheckbutton changes
The TabStrip control is used to present tabbed controls, which can be used along with the
MultiPage control to display varied information in a given space. The TabStrip control
renders tabs that users can click to switch between the different tabs. The MultiPage
control is used to display multipages of data in a given screen area. This control is
typically used with TabStrip control.
The System.Web.UI.Control class defines all the properties, events, and methods that are
common to all the WebForms controls. Some of the properties, methods and events of
control class are:
Properties:
ID: represents the control identifier to refer to the server control in programs
Parent: represents the parent control in the server control hierarchy
Visible: indicates whether or not a server control should be rendered on the page
Methods:
Dispose: cause a server control to perform final cleanup
Equals: used to check whether or not an object is the same as the current object.
FindControl: used to search a container for a specified server control.
ToString: used to return the string representation of current object
Event:
Init: is fired when a control is initialized.
Load: when the control is loaded in a page
Unload: when the control is unloaded from memory
Interfaces:
INamingContainer Interface: Provides data binding, templated control, Routes
events to its child control
IPostBackDataHandler interface: when it needs to update its state or raise events
on server after examining postback data
IPostBackEventHandler: when you want to transfer events that are generated on
the client side to server.
Product_ID :
Product Name:
Buy
Steps to be followed for creating custom control:
Select the Add web form option from the project menu. Then Add new item
dialog box appears
This step involves converting a web form to user control. Add the required control to the
form using toolbox and then edit the HML code of aspx file. The HTML file cannot
contain the HTML tags that include <Head>, <body>, <HTMl> and <form> tags. Also
need to change @ Page and @ Control directives. The typical code after doing all the
changes is as follows:
<tr valign=top>
<td height=37></td>
<td>
<asp:Label id=Label1 runat=”server”>Product_ID</asp:Label></td></tr>
<tr valign=top>
<td colspan=2 height=4></td>
<td rowspan=2>
<tr valign=top>
<td height=25></td>
<td>
<asp:Label id=Label2 runat=”server”>Product_Name</asp:Label></td></tr>
This steps involves changing the extension of the file to .ascx. To rename the file you
need to do these steps:
Rightclick the user control web form file in solution explorer window and select
rename from the shortcut menu
Open the web form page in which you want to add your user control.
This step involves adding user control to web forms page by adding the code:
<Acme:Product id=”MyProduct” runat=”Server” />
This code is to be placed in the script where you want the control to appear on the page.
Mostly it is placed in the <Body> of <Form> element
(i) RequiredFieldValidator
This validation control is used to check whether a server control added to a web form
page has a value or not.
Properties:
ControlToValidate: used to specify the ID of the control that is to be validated
ErrorMessage: to specify the error message that is displayed in the validation
summary control
Text: to specify the error message displayed by the control
Display: static: each validation control occupies space even when no error
message text is visible
Display:dynamic: When layout of page changes , it causes controls to move as
error message are displayed. Validation controls cannot occupy the same space,
so you must give each control a separate location on the page.
Method:
Validate: used to perform validation and set the IsValid Property
Sample code:
(ii) RegularExpressionValidator
This control is used to match the value entered in a web form field to a regular
expression. The regular expression can be the format of telephone number or email
address.
Properties:
ControlToValidate: used to specify the ID of the control that is to be validated
ErrorMessage: used to specify the error message that is displayed in the
Validation Summary control
ValidationExpression: used to specify the regular expression to use for validation
Methods:
Validate: used to perform validation and set the IsValid property
Sample Code:
(iii) CompareValidator
This control is used to perform comparisons between a values entered with another
value.
Properties:
ControlToCompare: used to specify the Id of control that will be used to compare
ControlToValidate: used to specify the Id of the control that is to be validated
ErrorMessage: used to specify the error message that is displayed in
ValidationSummary
ValueToCompare: specify the value used when performing comparison
Methods:
Validate: used to perform validation and set the IsValid property
Sample Code:
<asp:textbox id=”txtage” Value=”enter age” runat=”server />
<asp:CompareValidator id=”txtageValidator” runat=”server”
ControlToValidate=”txtage”
ValueToCompare=”0”
Type=”Integer”
Operator=”GreaterThanEqual”
ErrorMessage=”You must enter whole a number zero or greater”>
</asp:CompareValidator>
(iv) RangeValidator
This control is used to check whether the value of a particular web form field is within
the minimum and maximum data. The data can be dates, numbers, currency amounts or
strings.
Properties:
ControlToValidate: used to specify the Id of control that is to be validated
ErrorMessage: specify error that is displayed in validation summary
MaximumValue:specify maximum value in the range of values
MinimuValue:specify the minimum value in the range of values
Type: to set as currency, date, double, integer or string
Methods:
Validate: perform validation and set the IsValid property
Sample Code:
(v) ValidationSummary
This control is used to summarize all errors and display the error list in a user-specified
location in the web page.
Properties:
HeadText: to set the text that will be displayed at the top of summary
ShowMessageBox: to display the error message in a pop-up messagebox
ShowSummary: used to enable or disable the summary of error messages
Sample Code:
(vi) CustomValidator
Sample Code:
<asp:textbox id=”cardno” maxlength=”16” runat=”server”/>
<asp:CustomValidator id=”cucardno”
ControlToValidate=”cardno”
ClientValidationFunction=”IsCardValid”
Display=”dynamic”
Errormessage=”invalid card number”
Runat=”server”>
</asp:CustomValidator><br>
IsCardValid function:
<script language=”javascript”>
function IsCardValid(source, value){
if (value != “5555555555”)
return false;
else
return true;
}
</script>
The process of reviewing the code to identify the root cause of error and its elimination
is called debugging.
Access error:
• Use custom error pages: The HTML error page can be displayed to a user with
the steps given:
Create web page that you want to display error message [.html or .aspx]
Modify web.config file to show Myerror.aspx
<configuration>
<system.web>
<customErrors mode=”RemoteOnly”
defaultRedirect=”MyError.aspx”/>
</system.web>
</configuration>
• Tracking errors: To ensure that the administrators and developers are also able
to track errors. It is implemented by Application_Error event. For enabling this
Import System.Dianostics in Global.asax file. And write event log to track
errors.
• Import system.Io and write the code updation in Page_Load event to throw error.
Page level tracing: allows to write debug message directly to web form. The
system.web.TraceContext class support the trace functionality of ASP.Net page.
Application level tracing allow to trace the entire application. Enable the <Trace >
element of <system.web> element in applications <web.config> file.
The debug tool bar provided by VS.Net is used. The various debugging tools can be
accessed using the debug menu item. It allows to trace and rectify an error. The two
different ways to use debug tools:
To debug the current page, mark the page as startup page of project and Set the
breakpoint before browse the page.
To debug select Debug-> start. This option starts the application and attaches a
debugger.
When you enter values and proceeds the debugger enters break mode placed by
you.
In this mode, you can see the line at which you set the breakpoint being
highlighted. You can check the values of various variable and controls for
correctness in break mode.
You will now run through the procedure in a step wise manner to identify the
source of problem by selecting debug->step into.
You can stop debugging and correct the code. To stop the debug process, select
debug->stop debugging.
Attach
Debugger
Stop debugger
Repeat