0% found this document useful (0 votes)
4 views171 pages

Web Development Using .Netunit-4 FR

The document outlines the evolution of ASP.NET versions from 3.0 to 4.6, highlighting key features and enhancements such as new data controls, support for HTTP/2, and various development styles including Web Forms, MVC, and Web Pages. It explains the configuration of ASP.NET applications through machine.config and web.config files, detailing how settings can be overridden and the structure of these configuration files. Additionally, it describes the programming model of ASP.NET, emphasizing the differences between the Web Forms and MVC frameworks.

Uploaded by

parasmdu.ac24
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views171 pages

Web Development Using .Netunit-4 FR

The document outlines the evolution of ASP.NET versions from 3.0 to 4.6, highlighting key features and enhancements such as new data controls, support for HTTP/2, and various development styles including Web Forms, MVC, and Web Pages. It explains the configuration of ASP.NET applications through machine.config and web.config files, detailing how settings can be overridden and the structure of these configuration files. Additionally, it describes the programming model of ASP.NET, emphasizing the differences between the Web Forms and MVC frameworks.

Uploaded by

parasmdu.ac24
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

527

Web parts
Personalization services
Full pre-compilation
New localization
technique
Support for 64-bit
processors
Provider class model

November 21, 3.0 Windows Presentation


2006 Foundation (WPF)
Windows Workflow
Foundation (WF)
Windows
Communication
Foundation, which can
use [Link] to host
services
Windows CardSpace,
which uses [Link] for
login roles
528

November 19, 3.5 New data controls


2007 (ListView, DataPager)
[Link] AJAX
included as part of the
framework
Support for HTTP
pipelining and
syndication feeds.
WCF support for RSS,
JSON, POX and Partial
Trust
All the .NET Framework
3.5 changes, like LINQ
etc.

August 11, 2008 3.5 Service Incorporation of


Pack1 [Link] Dynamic Data
Support for controlling
browser history in an
[Link] AJAX
application
Ability to combine
multiple JavaScript files
into one file for more
efficient downloading
New namespaces
[Link]
and [Link]
529

April 12, 2010 4.0 The two new properties


added in the Page class
are MetaKeyword and
MetaDescription.

August 15, 2012 4.5

October 17, 4.5.1 Bootstrap 3.0


2013 Web API 2: OAuth 2.0,
OData improvements,
CORS
MVC 5: Attribute
routing, authentication
filters and filter overrides
EF 6
SignalR
OWIN

May 5, 2014 4.5.2 Higher reliability HTTP


header inspection and
modification methods
New way to schedule
background
asynchronous worker
tasks

July 20, 2015 4.6 HTTP/2 support when


running on Windows 10
More async task-
returning APIs
530

[Link] provides three development styles for creating web


applications:
1. Web Forms
2. [Link] MVC
3. [Link] Web Pages

Web Forms
It is an event driven development framework. It is used to
develop application with powerful data access. It provides
server side controls and events to create web application. It is
part of the [Link] framework. We will discuss it further in
next chapters.
[Link] MVC
It gives us a MVC (Model View Controller), patterns-based
way to build dynamic websites. It enables a clean separation
of concerns and that gives you full control over markup for
enjoyable, agile development. It also provides many features
that enable fast development for creating outstanding
applications. We will discuss it further in next chapters.
[Link] Web Pages
It is used to create dynamic web pages. It provides fast and
lightweight way to combine server code with HTML. It helps
to add video, link to the social sites. It also provides other
features like you can create beautiful sites that conform to the
latest web standards.
All these are stable and well equipped frameworks. We can
create web applications with any of them. These are also
531

based on the .NET Framework and share core functionalities


of .NET and [Link].
We can use any development style to create application. The
selection of style is depends on the skills and experience of
the programmer.
Although each framework is independent to other, we can
combine and use any of that at any level of our application.
For example, to develop client interaction module, we can use
MVC and for data control, we can use Web Forms.
The following table illustrates each development model.

Model Skills Development Experience


style

Web Forms Win Forms, Rapid Mid-Level,


WPF, .NET development Advanced
using a rich RAD
library of
controls that
encapsulate
HTML
markup
532

MVC Ruby on Full control Mid-Level,


Rails, .NET over HTML Advanced
markup, code
and markup
separated,
and easy to
write tests.
The best
choice for
mobile and
single-page
applications
(SPA).

Web Pages Classic ASP, HTML New, Mid-


PHP markup and Level
your code
together in
the same file

Configuring [Link] Application:


The behavior of an [Link] application is affected by
different settings in the configuration files:
• [Link]
• [Link]
The [Link] file contains default and the machine-
specific value for all supported settings. The machine settings
533

are controlled by the system administrator and applications


are generally not given access to this file.
An application however, can override the default values by
creating [Link] files in its roots folder. The [Link]
file is a subset of the [Link] file.
If the application contains child directories, it can define a
[Link] file for each folder. Scope of each configuration
file is determined in a hierarchical top-down manner.
Any [Link] file can locally extend, restrict, or override
any settings defined on the upper level.
Visual Studio generates a default [Link] file for each
project. An application can execute without a [Link] file,
however, you cannot debug an application without a
[Link] file.
The following figure shows the Solution Explorer for the
sample example used in the web services tutorial:
534

In this application, there are two [Link] files for two


projects i.e., the web service and the web site calling the web
service.
The [Link] file has the configuration element as the root
node. Information inside this element is grouped into two
main areas: the configuration section-handler declaration area,
and the configuration section settings area.
The following code snippet shows the basic syntax of a
configuration file:
<configuration>

<!-- Configuration section-handler declaration area. -->


<configSections>
<section name="section1" type="section1Handler" />
535

<section name="section2" type="section2Handler" />


</configSections>
<!-- Configuration section settings area. -->

<section1>
<s1Setting1 attribute1="attr1" />
</section1>

<section2>
<s2Setting1 attribute1="attr1" />
</section2>

<[Link]>
<authentication mode="Windows" />
</[Link]>

</configuration>
Configuration Section Handler declarations
The configuration section handlers are contained within the
<configSections> tags. Each configuration handler specifies
name of a configuration section, contained within the file,
which provides some configuration data. It has the following
basic syntax:
<configSections>
536

<section />
<sectionGroup />
<remove />
<clear/>
</configSections>
It has the following elements:
• Clear - It removes all references to inherited sections
and section groups.
• Remove - It removes a reference to an inherited section
and section group.
• Section - It defines an association between a
configuration section handler and a configuration
element.
• Section group - It defines an association between a
configuration section handler and a configuration
section.
Application Settings
The application settings allow storing application-wide name-
value pairs for read-only access. For example, you can define
a custom application setting as:
<configuration>
<appSettings>
<add key="Application Name" value="MyApplication" />
</appSettings>
</configuration>
537

For example, you can also store the name of a book and its
ISBN number:
<configuration>
<appSettings>
<add key="appISBN" value="0-273-68726-3" />
<add key="appBook" value="Corporate Finance" />
</appSettings>
</configuration>
Connection Strings
The connection strings show which database connection
strings are available to the website. For example:
<connectionStrings>
<add name="ASPDotNetStepByStepConnectionString"
connectionString="Provider=[Link].4.0;
Data Source=E:\\projects\datacaching\ /
datacaching\App_Data\[Link]"
providerName="[Link]" />

<add name="booksConnectionString"
connectionString="Provider=[Link].4.0;
Data Source=C:\ \databinding\App_Data\[Link]"
providerName="[Link]" />
</connectionStrings>
538

[Link] Element
The [Link] element specifies the root element for the
[Link] configuration section and contains configuration
elements that configure [Link] Web applications and
control how the applications behave.
It holds most of the configuration elements needed to be
adjusted in common applications. The basic syntax for the
element is as given:
<[Link]>
<anonymousIdentification>
<authentication>
<authorization>
<browserCaps>
<caching>
<clientTarget>
<compilation>
<customErrors>
<deployment>
<deviceFilters>
<globalization>
<healthMonitoring>
<hostingEnvironment>
<httpCookies>
<httpHandlers>
539

<httpModules>
<httpRuntime>
<identity>
<machineKey>
<membership>
<mobileControls>
<pages>
<processModel>
<profile>
<roleManager>
<securityPolicy>
<sessionPageState>
<sessionState>
<siteMap>
<trace>
<trust>
<urlMappings>
<webControls>
<webParts>
<webServices>
<xhtmlConformance>
</[Link]>
540

The following table provides brief description of some of


common sub elements of the [Link] element:
AnonymousIdentification
This is required to identify users who are not authenticated
when authorization is required.
Authentication
It configures the authentication support. The basic syntax is as
given:
<authentication mode="[Windows|Forms|Passport|None]">
<forms>...</forms>
<passport/>
</authentication>
Authorization
It configures the authorization support. The basic syntax is as
given:
<authorization>
<allow .../>
<deny .../>
</authorization>
Caching
It Configures the cache settings. The basic syntax is as given:
<caching>
<cache>...</cache>
<outputCache>...</outputCache>
541

<outputCacheSettings>...</outputCacheSettings>
<sqlCacheDependency>...</sqlCacheDependency>
</caching>
CustomErrors
It defines custom error messages. The basic syntax is as
given:
<customErrors defaultRedirect="url"
mode="On|Off|RemoteOnly">
<error. . ./>
</customErrors>
Deployment
It defines configuration settings used for deployment. The
basic syntax is as follows:
<deployment retail="true|false" />
HostingEnvironment
It defines configuration settings for hosting environment. The
basic syntax is as follows:
<hostingEnvironment idleTimeout="HH:MM:SS"
shadowCopyBinAssemblies="true|false"
shutdownTimeout="number"
urlMetadataSlidingExpiration="HH:MM:SS" />
Identity
It configures the identity of the application. The basic syntax
is as given:
542

<identity impersonate="true|false"
userName="domain\username"
password="<secure password>"/>
MachineKey
It configures keys to use for encryption and decryption of
Forms authentication cookie data.
It also allows configuring a validation key that performs
message authentication checks on view-state data and forms
authentication tickets. The basic syntax is:
<machineKey validationKey="AutoGenerate,IsolateApps"
[String]
decryptionKey="AutoGenerate,IsolateApps" [String]
validation="HMACSHA256" [SHA1 | MD5 | 3DES | AES |
HMACSHA256 |
HMACSHA384 | HMACSHA512 | alg:algorithm_name]
decryption="Auto" [Auto | DES | 3DES | AES |
alg:algorithm_name]
/>
Membership
This configures parameters of managing and authenticating
user accounts. The basic syntax is:
<membership defaultProvider="provider name"
userIsOnlineTimeWindow="number of minutes"
hashAlgorithmType="SHA1">
<providers>...</providers>
543

</membership>
Pages
It provides page-specific configurations. The basic syntax is:
<pages asyncTimeout="number"
autoEventWireup="[True|False]"
buffer="[True|False]"
clientIDMode="[AutoID|Predictable|Static]"
compilationMode="[Always|Auto|Never]"
controlRenderingCompatibilityVersion="[3.5|4.0]"
enableEventValidation="[True|False]"
enableSessionState="[True|False|ReadOnly]"
enableViewState="[True|False]"
enableViewStateMac="[True|False]"
maintainScrollPositionOnPostBack="[True|False]"
masterPageFile="file path"
maxPageStateFieldLength="number"
pageBaseType="typename, assembly"
pageParserFilterType="string"
smartNavigation="[True|False]"
styleSheetTheme="string"
theme="string"
userControlBaseType="typename"
validateRequest="[True|False]"
544

viewStateEncryptionMode="[Always|Auto|Never]" >

<controls>...</controls>
<namespaces>...</namespaces>
<tagMapping>...</tagMapping>
<ignoreDeviceFilters>...</ignoreDeviceFilters>
</pages>
Profile
It configures user profile parameters. The basic syntax is:
<profile enabled="true|false" inherits="fully qualified type
reference"
automaticSaveEnabled="true|false"
defaultProvider="provider name">

<properties>...</properties>
<providers>...</providers>

</profile>
RoleManager
It configures settings for user roles. The basic syntax is:
<roleManager cacheRolesInCookie="true|false"
cookieName="name"
cookiePath="/"
cookieProtection="All|Encryption|Validation|None"
545

cookieRequireSSL="true|false "
cookieSlidingExpiration="true|false "
cookieTimeout="number of minutes"
createPersistentCookie="true|false"
defaultProvider="provider name" domain="cookie
domain">
enabled="true|false"
maxCachedResults="maximum number of role names
cached"

<providers>...</providers>
</roleManager>
SecurityPolicy
It configures the security policy. The basic syntax is:
<securityPolicy>
<trustLevel />
</securityPolicy>
UrlMappings
It defines mappings to hide the original URL and provide a
more user friendly URL. The basic syntax is:
<urlMappings enabled="true|false">
<add.../>
<clear />
<remove.../>
546

</urlMappings>
WebControls
It provides the name of shared location for client scripts. The
basic syntax is:
<webControls clientScriptsLocation="String" />
WebServices
This configures the web services.

Programming Model :
[Link] is a web development framework for building web
pages and web application with HTML, Client side script,
Server side script etc. There are 3 models provided by [Link]
to build web application. Each model has different scope and
application of use, so I am going to explain about each model.

1. Web Form

This is basically an event driven programming model which


lets you build dynamic websites using familiar drag- and-
drop. Design view and lot many controls helps you to develop
application rapidly. This is a tradition approach to build
website in [Link]. Web Forms are compiled and executed on
the server, which generates the HTML that displays the web
pages. This Model basically targets to those developers who
prefer declarative and control based programming, such as
Win Form etc. Developer does not require a lot of experience
to develop application in this model. It is the most popular
model of [Link] but has been criticized for the lack of
547

control over the generated markup because a lot of


abstractions are present in this model. In this model each page
having aspx and .cs file. In aspx file we can write HTML tags,
Server controls etc. and all events and code written in .cs file.
So by maintaining two file this model separate code from
front end tags for generating UI. There are following
functionalities provided by this model.
• Use page controller pattern means each page has a code
behind class that act as a controller.
• Code behind file depends on View so both will combine
during execution.
• There is lots of server controls provided, so it is very
easy and fast development possible with this model.
• Deep understanding of HTML, CSS and JavaScript is not
required. With the basic knowledge of this you can start
development in this model because all these things are
abstract.
• This Model provides Rapid development
2. [Link] MVC

[Link] MVC is for developers who are interested in


development like test-driven development, separation of
concerns, inversion of control (IoC) etc. This framework
separates the business logic layer of a web application from its
presentation layer.

MVC is a framework for building web sites which uses MVC


(Model View Controller) design:
548

• The Model represents the behavior and data of


application logic
• The View displays the data and information
• The Controller handles the input from user and create
link between Model and View. Controller read data from
a view and sends input data to the model.
MVC helps you manage complex applications, because you
can focus on one aspect of an application at a time. For
example, you can focus on the view without depending on the
business logic. It also makes it easier to test an application.
That's why test driven development is easy with MVC
framework.

The MVC also facilitates the group development. Different


developers can work on the view, the controller logic, and the
business logic in parallel or if I want to explain in easy word
then I can say developers can work on Model, View and
controller separately and later on they can merge whole
application.

The MVC programming model is a lighter alternative to


[Link] Web Forms model. It is a lightweight, highly
testable framework, integrated with all existing [Link]
features, such as Master Pages, Authentication and Security.

This model uses Front Controller pattern. There is a single


central controller for all pages to process web application.
Developer should have good knowledge of HTML,CSS and
Javascript in order to work with this model.
549

3. Web Pages

Web Pages are the easiest programming model for developing


[Link] web pages. It provides an easy way to combine
HTML, CSS, and JavaScript and server code. It uses Razor
syntax to write server side and HTML. It is similar to PHP
and classic ASP. In this page Model you can create HTML
pages and then add server based code to page. It will be very
easy to those developers who have worked on PHP and not
having worked on [Link] before. There are following basic
features of this model.
• Easy to learn, understandand develop web application
• Built aroundsingle web pages
• Similar to PHPand Classic ASP pages
• Server scriptingwith Visual Basic or C#
• Full HTML, CSS,and JavaScript control
550

[Link] FRAMEWORK
Code Behind:
The [Link] Code Behind feature in .Net Framework allows
developers to separate the server-side code from the
presentation layer. This concept makes the server-side code to
store in one file and the presentation code, that is, HTML
code in another file. When you compile the [Link] page
both these files get compiled as a single entity. In the
traditional ASP model, this could not be achieved which often
leads to intermingling of the code and the design.

The biggest advantage, in [Link], is that the presentation


code will be in .aspx file and the server-side code will be in
any .Net compatible language such as Visual [Link], C#,
or J#. You can also do away with the presentation layer
because you can give this role to the web designers.

This saves time and you can concentrate only on the coding
part of the application. In addition, you can create a class for
your code and inherit this class from the [Link] Page
object. By this way the class can access the page intrinsics and
also interact with the postback architecture. After this you can
create the [Link] page and apply a page directive to inherit
from this new class.

But before you create an [Link] Code Behind class, you


have to reference it to a namespace. The namespace could be
[Link] or` [Link]. Next you
have to inherit the class from the Page object. You must
551

declare some public instances of server controls using the


name for the variables that are similar to the web controls.
This procedure will create a link between the [Link] Code
Behind class and the server controls.

You can use the [Link] Code Behind feature in various


web applications development tools such as Visual [Link]
and [Link] Web Matrix. They provide very easy ways to
use the [Link] Code Behind. After dragging and dropping
the server control from the Toolbox to the web page you can
just right click on it to view the [Link] Code Behind page.

Page Directives:
[Link] directives are instructions to specify optional
settings, such as registering a custom control and page
language. These settings describe how the web forms (.aspx)
or user controls (.ascx) pages are processed by the .Net
framework.
The syntax for declaring a directive is:
<%@ directive_name attribute=value [attribute=value] %>
In this section, we will just introduce the [Link] directives
and we will use most of these directives throughout the
tutorials.
The Application Directive
The Application directive defines application-specific
attributes. It is provided at the top of the [Link] file.
The basic syntax of Application directive is:
552

<%@ Application Language="C#" %>


The attributes of the Application directive are:

Attributes Description

Inherits The name of the class from which to inherit.

The text description of the application. Parsers


Description
and compilers ignore this.

Language The language used in code blocks.

The Assembly Directive


The Assembly directive links an assembly to the page or the
application at parse time. This could appear either in the
[Link] file for application-wide linking, in the page file, a
user control file for linking to a page or user control.
The basic syntax of Assembly directive is:
<%@ Assembly Name ="myassembly" %>
The attributes of the Assembly directive are:

Attributes Description

Name The name of the assembly to be linked.

The path to the source file to be linked and


Src
compiled dynamically.

The Control Directive


The control directive is used with the user controls and
appears in the user control (.ascx) files.
553

The basic syntax of Control directive is:


<%@ Control Language="C#" EnableViewState="false" %>
The attributes of the Control directive are:

Attributes Description

The Boolean value that enables or disables


AutoEventWireup
automatic association of events to handlers.

ClassName The file name for the control.

The Boolean value that enables or disables


Debug
compiling with debug symbols.

The text description of the control page,


Description
ignored by compiler.

The Boolean value that indicates whether view


EnableViewState
state is maintained across page requests.

For VB language, tells the compiler to use


Explicit
option explicit mode.

Inherits The class from which the control page inherits.

Language The language for code and script.

Src The filename for the code-behind class.

For VB language, tells the compiler to use the


Strict
option strict mode.
554

The Implements Directive


The Implement directive indicates that the web page, master
page or user control page must implement the specified .Net
framework interface.
The basic syntax for implements directive is:
<%@ Implements Interface="interface_name" %>
The Import Directive
The Import directive imports a namespace into a web page,
user control page of application. If the Import directive is
specified in the [Link] file, then it is applied to the entire
application. If it is in a page of user control page, then it is
applied to that page or control.
The basic syntax for import directive is:
<%@ namespace="[Link]" %>
The Master Directive
The Master directive specifies a page file as being the mater
page.
The basic syntax of sample MasterPage directive is:
<%@ MasterPage Language="C#" AutoEventWireup="true"
CodeFile="[Link]" Inherits="SiteMaster" %>
The MasterType Directive
The MasterType directive assigns a class name to the Master
property of a page, to make it strongly typed.
The basic syntax of MasterType directive is:
<%@ MasterType attribute="value"[attribute="value" ...] %>
555

The OutputCache Directive


The OutputCache directive controls the output caching
policies of a web page or a user control.
The basic syntax of OutputCache directive is:
<%@ OutputCache Duration="15" VaryByParam="None"
%>
The Page Directive
The Page directive defines the attributes specific to the page
file for the page parser and the compiler.
The basic syntax of Page directive is:
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="[Link]" Inherits="_Default"
Trace="true" %>
The attributes of the Page directive are:

Attributes Description

The Boolean value that enables or disables


AutoEventWireup page events that are being automatically bound
to methods; for example, Page_Load.

The Boolean value that enables or disables


Buffer
HTTP response buffering.

ClassName The class name for the page.

The browser for which the server controls


ClientTarget
should render content.
556

CodeFile The name of the code behind file.

The Boolean value that enables or disables


Debug
compilation with debug symbols.

The text description of the page, ignored by


Description
the parser.

It enables, disables, or makes session state


EnableSessionState
read-only.

The Boolean value that enables or disables


EnableViewState
view state across page requests.

URL for redirection if an unhandled page


ErrorPage
exception occurs.

Inherits The name of the code behind or other class.

Language The programming language for code.

Src The file name of the code behind class.

Trace It enables or disables tracing.

It indicates how trace messages are displayed,


TraceMode
and sorted by time or category.

Transaction It indicates if transactions are supported.


557

The Boolean value that indicates whether all


ValidateRequest input data is validated against a hardcoded list
of values.

The PreviousPageType Directive


The PreviousPageType directive assigns a class to a page, so
that the page is strongly typed.
The basic syntax for a sample PreviousPagetype directive is:
<%@ PreviousPageType attribute="value"[attribute="value"
...] %>
The Reference Directive
The Reference directive indicates that another page or user
control should be compiled and linked to the current page.
The basic syntax of Reference directive is:
<%@ Reference Page ="[Link]" %>
The Register Directive
The Register derivative is used for registering the custom
server controls and user controls.
The basic syntax of Register directive is:
<%@ Register Src="~/[Link]" TagName="footer"
TagPrefix="Tfooter" %>
Page Events:
class represents theclass containsIn [Link] Web Forms, the
Pageclass represents the page being requested and processed.
The Pageclass contains lifecycle events that handle the
processing of an HTTP request. The Pageevents are essential
558

for managing the page's behavior, rendering, and control


handling.
Here are the primary events in the [Link] page lifecycle:
Common Page Events in [Link] Web Forms
1. Page_Init,
o This event is triggered when the page is initialized,
before any controls are loaded.
o You can use this event to set up properties or
initialize variables for controls on the page.
Copy it
protected void Page_Init(object sender, EventArgs e)
{
// Code to initialize page or controls
}
2. Page_Load,
o The Page_Loadevent is triggered when the page is
loaded into memory. This is where you typically put
the logic that you want to execute every time the
page is requested (such as populating data).
o You should ensure that you check whether the page
is being loaded for the first time or if it's a postback.
Copy it
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
559

{
// Code to load data for the first time the page loads
}
}
3. Page_PreRender,
o This event occurs just before the page's content is
rendered to the client. It gives you the opportunity
to modify the page before it's displayed to the user.
o Typically used to change properties like visibility,
style, or content dynamically.
Copy it
protected void Page_PreRender(object sender, EventArgs e)
{
// Code to update the page before rendering
}
4. Page_Unload,
o This event occurs when the page has fully loaded
and is about to be unloaded from memory.
o It is rarely used, as it is typically for cleanup tasks.
Copy it
protected void Page_Unload(object sender, EventArgs e)
{
// Code to clean up resources
}
560

5. Page_Error,
o This event is triggered when an unhandled
exception occurs during the page's request. This is a
great place to handle errors gracefully and log them.
csharp
Copy it
protected void Page_Error(object sender, EventArgs e)
{
Exception ex = [Link]();
// Log the error or handle it here
[Link](); // Clears the error to prevent the
default error page
}
6. Page_Disposed,
o This event is triggered when the page's resources are
disposed of after the page has finished its request
lifecycle. It is used to release resources that were
explicitly allocated during the request.
csharp
Copy it
protected void Page_Disposed(object sender, EventArgs e)
{
// Code to clean up or release resources
}
561

Typical Page Lifecycle Flow:


1. Initialization ( Page_Init) – Initialize page properties
and controls.
2. Load ( Page_Load) – Load data and bind it to controls.
3. Postback Handling (within Page_Load) – Handle
postbacks (if the page is being loaded after a user
interaction).
4. PreRender ( Page_PreRender) – Prepare the page for
rendering, adjust properties or controls.
5. Render (Automatically done by the framework) –
Render the page to the output stream (HTML).
6. Unload ( Page_Unload) – Release any resources.
Example Usage in [Link] Web Forms
csharp
Copy it
public partial class MyPage : [Link]
{
// Page_Init is called during page initialization
protected void Page_Init(object sender, EventArgs e)
{
// Initialization logic
}

// Page_Load is called when the page is loaded


562

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
// Code to run only once during the first load
}
}

// Page_PreRender is called just before the page is rendered


protected void Page_PreRender(object sender, EventArgs
e)
{
// Modify the page before rendering
}

// Page_Error is called when there is an unhandled


exception
protected void Page_Error(object sender, EventArgs e)
{
// Handle error
Exception ex = [Link]();
// Log or display error
}
563

// Page_Disposed is called when the page is disposed


protected void Page_Disposed(object sender, EventArgs e)
{
// Clean up resources
}
}
Summary of Common Events:
Event Description When to Use
Called when the
Page_Init Initialize controls or_
page is initialized._
Called when the
Page_Load ,
page is loaded.
Called just before Modify controls,
Page_PreRender the page is finalize data binding
rendered_ before rendering.
called when the
Page_Unload Cleanup operations.
page_
Page_Error called when an_ Handle errors globally_
Called when the
Page_Disposed Release resources.
page is disposed_
By understanding these page events, you can effectively
control the behavior of your [Link] Web Forms pages
during their lifecycle.
564

Post Back:
PostBack is the name given to the process of submitting an
[Link] page to the server for processing. PostBack is done
if certain credentials of the page are to be checked against
some sources (such as verification of username and password
using a database). This is something that a client machine is
not able to accomplish, and thus these details have to be
'posted back' to the server.
What is AutoPostBack Property in [Link]
If we create a web page that consists of one or more Web
Controls that are configured to use AutoPostBack (Every Web
control will have its own AutoPostBack property), [Link]
adds a special JavaScipt function to the rendered HTML Page.
This function is named _doPostBack(). When Called, it
triggers a PostBack, sending data back to the web Server.
[Link] also adds two additional hidden input fields that are
used to pass information back to the server. This information
consists of the ID of the Control that raised the event and any
additional information if needed. These fields will empty
initially, as shown below,
<input type="hidden" name="__EVENTTARGET"
id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT"
id="__EVENTARGUMENT" value="" />
[Link] (C#)
Copy
The _doPostBack() function has the responsibility for setting
these values with the appropriate information about the event
565

and submitting the form. The _doPostBack() function is


shown below:
<script language="text/javascript">

function __doPostBack(eventTarget, eventArgument) {


if (![Link] || ([Link]() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value =
eventArgument;
[Link]();
}
</script>
JavaScript
[Link] generates the _doPostBack() function
automatically, provided at least one control on the page uses
automatic postbacks.
Any Control that has its AutoPostBack Property set to true is
connected to the _doPostBack() function using the onclick or
onchange attributes. These attributes indicate what action the
Browser should take in response to the Client-Side javascript
events onclick and onchange.
In other words, [Link] automatically converts a client-side
Javascript event into a server-side [Link] event, using the
_doPostBack() function as an intermediary.
Life Cycle of a Web Page
566

To work with the [Link] Web Controls events, we need a


solid understanding of the web page life cycle. The following
actions will take place when a user changes a control that has
the AutoPostBack property set to true.
1. On the client side, the JavaScript _doPostBack function
is invoked, and the page is resubmitted to the server.
2. [Link] re-creates the Page object using the .aspx file.
3. [Link] retrieves state information from the hidden
view state field and updates the controls accordingly.
4. The Page. Load event is fired.
5. The appropriate change event is fired for the control. (If
more than one control has been changed, the order of
change events is undetermined.)
6. The [Link] event fires and the page is rendered
(transformed from a set of objects to an HTML page).
7. Finally, the Page. The unloading event is fired.
8. The new page is sent to the client.
To watch these events in action, we can create a simple event
tracker application. All this application does is write a new
entry to a list control every time one of the events it's
monitoring occurs. This allows you to see the order in which
events are triggered.
567

Event Tracker Web Page


I have shown Markup codes and C# Codes below to make this
work.
[Link]
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="[Link]" Inherits="EventTracker"
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0


Transitional//EN"
"[Link]
[Link]">
568

<html xmlns="[Link]
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<p>
<h1>Controls being monitored for change
events:</h1>
<asp:TextBox ID="txt" runat="server"
AutoPostBack="true" OnTextChanged="CtrlChanged" />
<br /><br />
<asp:CheckBox ID="chk" runat="server"
AutoPostBack="true" OnCheckedChanged="CtrlChanged" />
<br /><br />
<asp:RadioButton ID="opt1" runat="server"
GroupName="Sample" AutoPostBack="true"
OnCheckedChanged="CtrlChanged" />
<asp:RadioButton ID="opt2" runat="server"
GroupName="Sample" AutoPostBack="true"
OnCheckedChanged="CtrlChanged" />
<h1>List of events:</h1>
<asp:ListBox ID="lstEvents" runat="server"
Width="355px" Height="150px" /><br />
<br /><br /><br />
569

</p>
</form>
</body>
</html>
C#
Copy
[Link]
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];

public partial class EventTracker : [Link]


{
protected void Page_Load(object sender, EventArgs e)
{
Log("<< Page_Load >>");
570

protected void Page_PreRender(object sender, EventArgs


e)
{
// When the [Link] event occurs, it is too late to
change the list.
Log("Page_PreRender");
}

protected void CtrlChanged(Object sender, EventArgs e)


{
// Find the control ID of the sender.
// This requires converting the Object type into a Control
class.
string ctrlName = ((Control)sender).ID;
Log(ctrlName + " Changed");
}

private void Log(string entry)


{
[Link](entry);
// Select the last item to scroll the list so the most recent
// entries are visible.
571

[Link] = [Link] - 1;
}
}
572

[Link] CONTROLS
Basic Web Server Controls:
[Link] provides web forms controls that are used to create
HTML components. These controls are categories as server
and client based. The following table contains the server
controls for the web forms.

Control Name Applicable Events Description

Label None It is used to


display text on
the HTML page.

TextBox TextChanged It is used to


create a text
input in the form.

Button Click, Command It is used to


create a button.

LinkButton Click, Command It is used to


create a button
that looks similar
to the hyperlink.

ImageButton Click It is used to


create an
imagesButton.
Here, an image
573

works as a
Button.

Hyperlink None It is used to


create a
hyperlink control
that responds to a
click event.

DropDownList SelectedIndexChanged It is used to


create a
dropdown list
control.

ListBox SelectedIndexCnhaged It is used to


create a ListBox
control like the
HTML control.

DataGrid CancelCommand, It used to create a


EditCommand, frid that is used
DeleteCommand, to show data. We
ItemCommand, can also perform
SelectedIndexChanged, paging, sorting,
PageIndexChanged, and formatting
SortCommand, very easily with
UpdateCommand, this control.
ItemCreated,
ItemDataBound
574

DataList CancelCommand, It is used to


EditCommand, create datalist
DeleteCommand, that is non-
ItemCommand, tabular and used
SelectedIndexChanged, to show data.
UpdateCommand,
ItemCreated,
ItemDataBound

CheckBox CheckChanged It is used to


create checkbox.

CheckBoxList SelectedIndexChanged It is used to


create a group of
check boxes that
all work together.

RadioButton CheckChanged It is used to


create radio
button.

RadioButtonList SelectedIndexChanged It is used to


create a group of
radio button
controls that all
work together.

Image None It is used to show


image within the
page.
575

Panel None It is used to


create a panel
that works as a
container.

PlaceHolder None It is used to set


placeholder for
the control.

Calendar SelectionChanged, It is used to


VisibleMonthChanged, create a calendar.
DayRender We can set the
default date,
move forward
and backward
etc.

AdRotator AdCreated It allows us to


specify a list of
ads to display.
Each time the
user re-displays
the page.

Table None It is used to


create table.

XML None It is used to


display XML
documents
576

within the
HTML.

Literal None It is like a label


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

Data List Web Server Controls:


The [Link] DataList control is a light weight server side
control that works as a container for data items. It is used to
display data into a list format to the web pages.
It displays data from the data source. The data source can be
either a DataTable or a table from database.
Here, first, we are creating DataList that gets data from a
DataTable. This example includes the following files.

[Link] DataList Example with DataTable


// [Link]
1. <%@ Page Language="C#" AutoEventWireup="true" C
odeBehind="[Link]"
2. Inherits="DataListExample.DataListExample2" %>
577

3. <!DOCTYPE html>
4. <html xmlns="[Link]
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. <p>The DataList shows data of DataTable</
p>
12. </div>
13. <asp:DataList ID="DataList1" runat="server">

14. <ItemTemplate>
15. <table cellpadding="2" cellspacing="0" b
order="1" style="width: 300px; height: 100px;
16. border: dashed 2px #04AFEF; backgroun
d-color: #FFFFFF">
17. <tr>
18. <td>
19. <b>ID: </b><span class="city"><
%# Eval("ID") %></span><br />
20. <b>Name: </b><span class="post
al"><%# Eval("Name") %></span><br />
578

21. <b>Email: </b><span class="coun


try"><%# Eval("Email")%></span><br />
22. </td>
23. </tr>
24. </table>
25. </ItemTemplate>
26. </asp:DataList>
27. </form>
28. </body>
29. </html>
CodeBehind
// [Link]
1. using System;
2. using [Link];
3. using [Link];
4. using [Link];
5. using [Link];
6. using [Link];
7. using [Link];
8. namespace DataListExample
9. {
10. public partial class DataListExample2 : System.
[Link]
579

11. {
12. protected void Page_Load(object sender, Eve
ntArgs e)
13. {
14. DataTable table = new DataTable();
15. [Link]("ID");
16. [Link]("Name");
17. [Link]("Email");
18. [Link]("101", "Sachin Kumar", "sa
chin@[Link]");
19. [Link]("102", "Peter", "peter@exa
[Link]");
20. [Link]("103", "Ravi Kumar", "ravi
@[Link]");
21. [Link]("104", "Irfan", "irfan@exa
[Link]");
22. [Link] = table;
23. [Link]();
24. }
25. }
26. }
Output:
It produces the following output to the browser.
580

[Link] DataList Example with database


This example gets data from the database table and includes
the following steps.
1) Add a Web Form
Add a web form to drag the DataList over it as we did in the
following screen shot.
581

Select DataList from the data category of the toolbox.

Drag the DataList to the form. After dragging, it looks like the
following.
582

Now, we need to configure database connection. Click on it


and set new data source.

It will pop up a new window with various Data Sources.


Select SQL database and click ok.
583

After selecting Data Source, now, we need to select data


connection. But before proceeding further add connection
string to the [Link] file.
// [Link]
1. <connectionStrings>
2. <add name="DefaultConnection" connectionString="
Data Source=(LocalDb)\MSSQLLocalDB;
3. AttachDbFilename=|DataDirectory|\aspnet-
[Link];
4. Initial Catalog=aspnet-AdoNetExample-
20170712102014;Integrated Security=True"
5. providerName="[Link]" />
6. <add name="StudentConnectionString"
584

7. connectionString="Data Source=DESKTOP-
EDFPJEL;Initial Catalog=Student;Integrated Security=T
rue"
8. providerName="[Link]" />
9. </connectionStrings>
Data Source is the name of the connection that is required to
connect SQL Server. It can be different for other computer
systems.

After clicking next, it asks to configure select statement.


585

It allows us to select number of columns to fetch custom


record. It also provides * option to select all columns records.
Now, test the configured query, is it working or not, as we did
in the below screenshot.
586

After finishing configuration, our DataList looks like this:

This "[Link]" file contains the following


code.
587

1. <%@ Page Language="C#" AutoEventWireup="true"


2. CodeBehind="[Link]" Inherits="Ado
[Link]" %>
3. <!DOCTYPE html>
4. <html xmlns="[Link]
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. </div>
12. <asp:DataList ID="DataList1" runat="server"
DataSourceID="SqlDataSource1">
13. <ItemTemplate>
14. name:
15. <asp:Label ID="nameLabel" runat="serve
r" Text='<%# Eval("name") %>' />
16. <br />
17. email:
18. <asp:Label ID="emailLabel" runat="serve
r" Text='<%# Eval("email") %>' />
19. <br />
20. contact:
588

21. <asp:Label ID="contactLabel" runat="ser


ver" Text='<%# Eval("contact") %>' />
22. <br />
23. <br />
24. </ItemTemplate>
25. </asp:DataList>
26. <asp:SqlDataSource ID="SqlDataSource1" run
at="server" ConnectionString="<%$
27. ConnectionStrings:StudentConnectionString %
>"
28. SelectCommand="SELECT * FROM [student]
"></asp:SqlDataSource>
29. </form>
30. </body>
31. </html>
Output:
This application produces the following output.
589

Web Server Control:


Calendar Control:
It is used to display selectable date in a calendar. It also shows
data associated with specific date. This control displays a
calendar through which users can move to any day in any
year.
We can also set Selected Date property that shows specified
date in the calendar.
To create Calendar we can drag it from the toolbox of visual
studio.
590

This is a server side control and [Link] provides own tag


to create it. The example is given below.
1. < asp:CalendarID="Calendar1" runat="server" SelectedD
ate="2017-06-15" ></asp:Calendar>
Server renders it as the HTML control and produces the
following code to the browser.
1. <table id="Calendar1" cellspacing="0" cellpadding="2" t
itle="Calendar"
2. style="border-width:1px;border-style:solid;border-
collapse:collapse;">
3. <tr><td colspan="7" style="background-color:Silver;">
4. <table cellspacing="0" style="width:100%;border-
collapse:collapse;">
5. <tr><td style="width:15%;">
6. <a href="javascript:__doPostBack('Calendar1','V6330')"

7. style="color:Black" title="Go to the previous month"></


a> ...
This control has its own properties that are tabled below.

Property Description

AccessKey It is used to set keyboard sho


control.

TabIndex The tab order of the control.


591

BackColor It is used to set background c


control.

BorderColor It is used to set border color


control.

BorderWidth It is used to set width of bord


control.

Font It is used to set font for the c

ForeColor It is used to set color of the c

Text It is used to set text to be sho


control.

ToolTip It displays the text when mo


the control.

Visible To set visibility of control on

Height It is used to set height of the

Width It is used to set width of the

NextMonth Text It is used to set text for the n


button.

TitleFormat It sets format for month title


592

DayHeaderStyle It is used to set style for the


row.

DayStyle It is used to apply style to da

NextPrevStyle It is used to apply style to th


navigation buttons.

Calendar Property Window

Example
In this example, we are implementing calendar and displaying
user selected date to the web page.
593

// [Link]
1. <%@ Page Language="C#" AutoEventWireup="true" C
odeBehind="[Link]"
2. Inherits="[Link]" %>
3. <!DOCTYPE html>
4. <html xmlns="[Link]
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <h2>Select Date from the Calender</h2>
11. <div>
12. <asp:Calendar ID="Calendar1" runat="serve
r"
13. OnSelectionChanged="Calendar1_Selection
Changed"></asp:Calendar>
14. </div>
15. </form>
16. <p>
17. <asp:Label runat="server" ID="ShowDate" ><
/asp:Label>
18. </p>
19. </body>
594

20. </html>
Code Behind
// [Link]
1. using System;
2. using [Link];
3. using [Link];
4. using [Link];
5. using [Link];
6. using [Link];
7. namespace WebFormsControlls
8. {
9. public partial class WebControls : [Link]
e
10. {
11. public void Calendar1_SelectionChanged(obje
ct sender, EventArgs e)
12. {
13. [Link] = "You Selected: "+Calenda
[Link]("D");
14. }
15. }
16. }
Output:
This view shows calendar to the browser.
595

It shows date selected by the user at the web page. A


screenshot is attached below.

Ad Rotator Control:
The AdRotator control randomly selects banner graphics from
a list, which is specified in an external XML schedule file.
596

This external XML schedule file is called the advertisement


file.
The AdRotator control allows you to specify the
advertisement file and the type of window that the link should
follow in the AdvertisementFile and the Target property
respectively.
The basic syntax of adding an AdRotator is as follows:
<asp:AdRotator runat = "server" AdvertisementFile =
"[Link]" Target = "_blank" />
Before going into the details of the AdRotator control and its
properties, let us look into the construction of the
advertisement file.
The Advertisement File
The advertisement file is an XML file, which contains the
information about the advertisements to be displayed.
Extensible Markup Language (XML) is a W3C standard for
text document markup. It is a text-based markup language that
enables you to store data in a structured format by using
meaningful tags. The term 'extensible' implies that you can
extend your ability to describe a document by defining
meaningful tags for the application.
XML is not a language in itself, like HTML, but a set of rules
for creating new markup languages. It is a meta-markup
language. It allows developers to create custom tag sets for
special uses. It structures, stores, and transports the
information.
Following is an example of XML file:
597

<BOOK>
<NAME> Learn XML </NAME>
<AUTHOR> Samuel Peterson </AUTHOR>
<PUBLISHER> NSS Publications </PUBLISHER>
<PRICE> $30.00</PRICE>
</BOOK>
Like all XML files, the advertisement file needs to be a
structured text file with well-defined tags delineating the data.
There are the following standard XML elements that are
commonly used in the advertisement file:

Element Description

Advertisements Encloses the advertisement file.

Ad Delineates separate ad.

ImageUrl The path of image that will be displayed.

The link that will be followed when the user


NavigateUrl
clicks the ad.

The text that will be displayed instead of the


AlternateText
picture if it cannot be displayed.

Keyword identifying a group of


Keyword
advertisements. This is used for filtering.
598

The number indicating how often an


Impressions
advertisement will appear.

Height Height of the image to be displayed.

Width Width of the image to be displayed.

Apart from these tags, customs tags with custom attributes


could also be included. The following code illustrates an
advertisement file [Link]:
<Advertisements>
<Ad>
<ImageUrl>[Link]</ImageUrl>

<NavigateUrl>[Link]
<AlternateText>
Order flowers, roses, gifts and more
</AlternateText>
<Impressions>20</Impressions>
<Keyword>flowers</Keyword>
</Ad>

<Ad>
<ImageUrl>[Link]</ImageUrl>
599

<NavigateUrl>[Link]
rl>
<AlternateText>Order roses and flowers</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>

<Ad>
<ImageUrl>[Link]</ImageUrl>

<NavigateUrl>[Link]
rl>
<AlternateText>Send flowers to Russia</AlternateText>
<Impressions>20</Impressions>
<Keyword>russia</Keyword>
</Ad>

<Ad>
<ImageUrl>[Link]</ImageUrl>

<NavigateUrl>[Link]
<AlternateText>Edible Blooms</AlternateText>
<Impressions>20</Impressions>
600

<Keyword>gifts</Keyword>
</Ad>
</Advertisements>
Properties and Events of the AdRotator Class
The AdRotator class is derived from the WebControl class
and inherits its properties. Apart from those, the AdRotator
class has the following properties:

Properties Description

AdvertisementFile The path to the advertisement file.

The element name of the field where alternate


AlternateTextFeild text is provided. The default value is
AlternateText.

The name of the specific list of data to be


DataMember
bound when advertisement file is not used.

DataSource Control from where it would retrieve data.

Id of the control from where it would retrieve


DataSourceID
data.

Specifies the font properties associated with


Font
the advertisement banner control.

The element name of the field where the URL


ImageUrlField for the image is provided. The default value is
ImageUrl.
601

KeywordFilter For displaying the keyword based ads only.

The element name of the field where the URL


NavigateUrlField to navigate to is provided. The default value is
NavigateUrl.

The browser window or frame that displays the


Target
content of the page linked.

Obtains the unique, hierarchically qualified


UniqueID
identifier for the AdRotator control.

Following are the important events of the AdRotator class:

Events Description

It is raised once per round trip to the server


AdCreated after creation of the control, but before the
page is rendered

Occurs when the server control binds to a data


DataBinding
source.

Occurs after the server control binds to a data


DataBound
source.

Occurs when a server control is released from


memory, which is the last stage of the server
Disposed
control lifecycle when an [Link] page is
requested
602

Occurs when the server control is initialized,


Init
which is the first step in its lifecycle.

Occurs when the server control is loaded into


Load
the Page object.

Occurs after the Control object is loaded but


PreRender
prior to rendering.

Occurs when the server control is unloaded


Unload
from memory.

Working with AdRotator Control


Create a new web page and place an AdRotator control on it.
<form id="form1" runat="server">
<div>
<asp:AdRotator ID="AdRotator1" runat="server"
AdvertisementFile ="~/[Link]"
onadcreated="AdRotator1_AdCreated" />
</div>
</form>
The [Link] file and the image files should be located in the
root directory of the web site.
Try to execute the above application and observe that each
time the page is reloaded, the ad is changed.
603

Validation Controls:
[Link] validation controls validate the user input data to
ensure that useless, unauthenticated, or contradictory data
don't get stored.
[Link] provides the following validation controls:
• RequiredFieldValidator
• RangeValidator
• CompareValidator
• RegularExpressionValidator
• CustomValidator
• ValidationSummary
BaseValidator Class
The validation control classes are inherited from the
BaseValidator class hence they inherit its properties and
methods. Therefore, it would help to take a look at the
properties and the methods of this base class, which are
common for all the validation controls:

Members Description

ControlToValidate Indicates the input control to validate.

Display Indicates how the error message is shown.

Indicates whether client side validation will


EnableClientScript
take.
604

Enabled Enables or disables the validator.

ErrorMessage Indicates error string.

Text Error text to be shown if validation fails.

Indicates whether the value of the control is


IsValid
valid.

It indicates whether in case of an invalid


SetFocusOnError control, the focus should switch to the related
input control.

The logical group of multiple validators, where


ValidationGroup
this control belongs.

This method revalidates the control and


Validate()
updates the IsValid property.

RequiredFieldValidator Control
The RequiredFieldValidator control ensures that the required
field is not empty. It is generally tied to a text box to force
input into the text box.
The syntax of the control is as given:
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
605

</asp:RequiredFieldValidator>
RangeValidator Control
The RangeValidator control verifies that the input value falls
within a predetermined range.
It has three specific properties:

Properties Description

It defines the type of the data. The available


Type values are: Currency, Date, Double, Integer,
and String.

MinimumValue It specifies the minimum value of the range.

MaximumValue It specifies the maximum value of the range.

The syntax of the control is as given:


<asp:RangeValidator ID="rvclass" runat="server"
ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)"
MaximumValue="12"
MinimumValue="6" Type="Integer">

</asp:RangeValidator>
CompareValidator Control
The CompareValidator control compares a value in one
control with a fixed value or a value in another control.
It has the following specific properties:
606

Properties Description

Type It specifies the data type.

It specifies the value of the input control to


ControlToCompare
compare with.

ValueToCompare It specifies the constant value to compare with.

It specifies the comparison operator, the


available values are: Equal, NotEqual,
Operator
GreaterThan, GreaterThanEqual, LessThan,
LessThanEqual, and DataTypeCheck.

The basic syntax of the control is as follows:


<asp:CompareValidator ID="CompareValidator1"
runat="server"
ErrorMessage="CompareValidator">

</asp:CompareValidator>
RegularExpressionValidator
The RegularExpressionValidator allows validating the input
text by matching against a pattern of a regular expression. The
regular expression is set in the ValidationExpression property.
The following table summarizes the commonly used syntax
constructs for regular expressions:
607

Character
Description
Escapes

\b Matches a backspace.

\t Matches a tab.

\r Matches a carriage return.

\v Matches a vertical tab.

\f Matches a form feed.

\n Matches a new line.

\ Escape character.

Apart from single character match, a class of characters could


be specified that can be matched, called the metacharacters.

Metacharacters Description

. Matches any character except \n.

[abcd] Matches any character in the set.

[^abcd] Excludes any character in the set.

[2-7a-mA-M] Matches any character specified in the range.

Matches any alphanumeric character and


\w
underscore.
608

\W Matches any non-word character.

Matches whitespace characters like, space, tab,


\s
new line etc.

\S Matches any non-whitespace character.

\d Matches any decimal character.

\D Matches any non-decimal character.

Quantifiers could be added to specify number of times a


character could appear.

Quantifier Description

* Zero or more matches.

+ One or more matches.

? Zero or one matches.

{N} N matches.

{N,} N or more matches.

{N,M} Between N and M matches.

The syntax of the control is as given:


<asp:RegularExpressionValidator ID="string" runat="server"
ErrorMessage="string"
ValidationExpression="string" ValidationGroup="string">
609

</asp:RegularExpressionValidator>
CustomValidator
The CustomValidator control allows writing application
specific custom validation routines for both the client side and
the server side validation.
The client side validation is accomplished through the
ClientValidationFunction property. The client side validation
routine should be written in a scripting language, such as
JavaScript or VBScript, which the browser can understand.
The server side validation routine must be called from the
control's ServerValidate event handler. The server side
validation routine should be written in any .Net language, like
C# or [Link].
The basic syntax for the control is as given:
<asp:CustomValidator ID="CustomValidator1"
runat="server"
ClientValidationFunction=.cvf_func.
ErrorMessage="CustomValidator">

</asp:CustomValidator>
ValidationSummary
The ValidationSummary control does not perform any
validation but shows a summary of all errors in the page. The
summary displays the values of the ErrorMessage property of
all validation controls that failed validation.
610

The following two mutually inclusive properties list out the


error message:
• ShowSummary : shows the error messages in specified
format.
• ShowMessageBox : shows the error messages in a
separate window.
The syntax for the control is as given:
<asp:ValidationSummary ID="ValidationSummary1"
runat="server"
DisplayMode = "BulletList" ShowSummary = "true"
HeaderText="Errors:" />
Validation Groups
Complex pages have different groups of information provided
in different panels. In such situation, a need might arise for
performing validation separately for separate group. This kind
of situation is handled using validation groups.
To create a validation group, you should put the input controls
and the validation controls into the same logical group by
setting their ValidationGroup property.
Example
The following example describes a form to be filled up by all
the students of a school, divided into four houses, for electing
the school president. Here, we use the validation controls to
validate the user input.
This is the form in design view:
611

The content file code is as given:


<form id="form1" runat="server">

<table style="width: 66%;">

<tr>
<td class="style1" colspan="3" align="center">
<asp:Label ID="lblmsg"
Text="President Election Form : Choose your
president"
runat="server" />
</td>
</tr>

<tr>
<td class="style3">
Candidate:
612

</td>

<td class="style2">
<asp:DropDownList ID="ddlcandidate"
runat="server" style="width:239px">
<asp:ListItem>Please Choose a
Candidate</asp:ListItem>
<asp:ListItem>M H Kabir</asp:ListItem>
<asp:ListItem>Steve Taylor</asp:ListItem>
<asp:ListItem>John Abraham</asp:ListItem>
<asp:ListItem>Venus Williams</asp:ListItem>
</asp:DropDownList>
</td>

<td>
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
</td>
</tr>
613

<tr>
<td class="style3">
House:
</td>

<td class="style2">
<asp:RadioButtonList ID="rblhouse" runat="server"
RepeatLayout="Flow">
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
</asp:RadioButtonList>
</td>

<td>
<asp:RequiredFieldValidator ID="rfvhouse"
runat="server"
ControlToValidate="rblhouse"
ErrorMessage="Enter your house name" >
</asp:RequiredFieldValidator>
<br />
</td>
</tr>
614

<tr>
<td class="style3">
Class:
</td>

<td class="style2">
<asp:TextBox ID="txtclass"
runat="server"></asp:TextBox>
</td>

<td>
<asp:RangeValidator ID="rvclass"
runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)"
MaximumValue="12"
MinimumValue="6" Type="Integer">
</asp:RangeValidator>
</td>
</tr>

<tr>
<td class="style3">
615

Email:
</td>

<td class="style2">
<asp:TextBox ID="txtemail" runat="server"
style="width:250px">
</asp:TextBox>
</td>

<td>
<asp:RegularExpressionValidator ID="remail"
runat="server"
ControlToValidate="txtemail" ErrorMessage="Enter
your email"
ValidationExpression="\w+([-+.']\w+)*@\w+([-
.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
</td>
</tr>

<tr>
<td class="style3" align="center" colspan="3">
<asp:Button ID="btnsubmit" runat="server"
onclick="btnsubmit_Click"
616

style="text-align: center" Text="Submit"


style="width:140px" />
</td>
</tr>
</table>
<asp:ValidationSummary ID="ValidationSummary1"
runat="server"
DisplayMode ="BulletList" ShowSummary ="true"
HeaderText="Errors:" />
</form>
The code behind the submit button:
protected void btnsubmit_Click(object sender, EventArgs e)
{
if ([Link])
{
[Link] = "Thank You";
}
else
{
[Link] = "Fill up all the fields";
}
}
617

PERFORMING DATA ACCESS


Data Bound Controls:
Databound controls are used to display data to the end-user
within the web applications and using databound controls
allows you to manipulate the data within the web applications
very easily.

Databound controls are bound to the DataSource property.


Databound controls are composite controls that combine other
[Link] Controls like Text boxes, Radio buttons, Buttons
and so on.

Frequently used Databound controls:

• Repeater
• DataList
• GridView
• List View
• Form View
Repeater

• Repeater controls is a Databound control to just display


data in the web application, using this we cannot
manipulate the data; in other words, a Repeater is a read-
only control.
• Repeater is very light-weight and faster to display data
compared with other controls, so whenever you just want
618

to display a repeated list of items then use a Repeater


Control.
• Repeater control works by repeating using the data
source.
• Repeater Control appearance is controlled by its
templates
Itemtemplate: An Itemtemplate represents items in a Data
Source; an Itemtemplate renders in the web page as a number
of records from the Datasource Collection

Alternatiningtemplate: Applies a background-color or


border-styles to alternative rows in the Data Source collection

Headertemplate: HeaderTemplate is used to provide


Headertext for the data source collection

Footertemplate: Display footer text to the Data Source.

Example to demonstrate Repeater Control:

[Link]
619

1. <%@ Page Language="C#" AutoEventWireup="true" C


odeFile="[Link]" Inherits="DataRea
pterDemo" %>
2. <!DOCTYPE html PUBLIC "-
//W3C//DTD XHTML 1.0 Transitional//EN" "[Link]
[Link]/TR/xhtml1/DTD/[Link]">
3. <html
4. xmlns="[Link]
5. <head runat="server">
6. <title></title>
7. <style>
8. tr {
9. height:40px;
10. }
11. </style>
12. </head>
13. <body>
14. <form id="form1" runat="server">
15. <div>
16. <center>
17. <div style=" border: 2px solid red;text-
align: left;border-radius: 2px;Padding-
top: 3px;background-color: Lime;width: 500px;border-
radius: 8px;font-size: 20px;">
620

18. <asp:Repeater ID="rp1" runat="serv


er">
19. <HeaderTemplate>
20. <table style="width:500px;pad
ding-top:0px;Background-color:Gold" >
21. <tr>
22. <td style="font-
size: 26px;
23. text-align: center;
24. height: 48px;">
25. <asp:Label ID="lblhdr"
runat="server" Text = "Student Profile"></asp:Label>
26. </td>
27. </tr>
28. </table>
29. </HeaderTemplate>
30. <ItemTemplate>
31. <table style="width:500px;">
32. <tr>
33. <td>
34. <asp:Label ID="lblempi
d1" runat="server" Text="Employee ID:"></asp:Label>
35. </td>
36. <td>
621

37. <asp:Label ID="lblempi


d2" runat="server" Text='<%# Eval("EmpId") %>'>
38. </asp:Label>
39. </td>
40. <td rowspan="5">
41. <asp:Image ID="img1" r
unat="server" Width="100px" ImageUrl= '
42. <%#"~/images/" + Ev
al("EmpImage") %>'/>
43. </td>
44. </tr>
45. <tr>
46. <td>
47. <asp:Label ID="lblem
pname1" runat="server" Text="Employee Name"></asp:
Label>
48. </td>
49. <td>
50. <asp:Label ID="lblem
pname2" runat="server" Text='<%# Eval("EmpName")
%>'>
51. </asp:Label>
52. </td>
53. </tr>
54. <tr>
622

55. <td>
56. <asp:Label ID="lble
mpemailId1" runat="server" Text="Employee EmailId">
</asp:Label>
57. </td>
58. <td>
59. <asp:Label ID="lblem
pemailId2" runat="server" Text='<%# Eval("EmpEmailI
d") %>'>
60. </asp:Label>
61. </td>
62. </tr>
63. <tr>
64. <td>
65. <asp:Label ID="lblem
pmob1" runat="server" Text="Mobile Number"></asp:L
abel>
66. </td>
67. <td>
68. <asp:Label ID="lblem
pmob2" runat="server" Text='<%# Eval("EmpMobileNu
m") %>'>
69. </asp:Label>
70. </td>
71. </tr>
623

72. <tr>
73. <td>
74. <asp:Label ID="lblem
pgen1" runat="server" Text="Gender"></asp:Label>
75. </td>
76. <td>
77. <asp:Label ID="lblem
pgen2" runat="server" Text='<%# Eval("EmpGender")
%>'>
78. </asp:Label>
79. </td>
80. </tr>
81. </table>
82. </ItemTemplate>
83. <FooterTemplate>
84. <table>
85. <tr>
86. <td>
87. @Developed by Abhish
ek Uppula
88. </td>
89. </tr>
90. </table>
91. </FooterTemplate>
624

92. </asp:Repeater>
93. </div>
94. </center>
95. </div>
96. </form>
97. </body>
98. </html>
[Link]
1. using System;
2. using [Link];
3. using [Link];
4. using [Link];
5.
6. using [Link];
7. using [Link];
8. using [Link];
9.
10. public partial class DataReapterDemo : [Link]
.[Link]
11. {
12. SqlConnection con = new SqlConnection(WebCo
[Link]["myconnection"]
.ConnectionString);
625

13. protected void Page_Load(object sender, EventAr


gs e)
14. {
15. if (!IsPostBack)
16. {
17. Bind();
18. } }
19.
20.
21. public void Bind()
22. {
23. SqlCommand cmd = new SqlCommand("select
* from Employee where EmpId = 1200",con);
24. SqlDataAdapter da = new SqlDataAdapter(cm
d);
25. DataSet ds = new DataSet();
26. [Link](ds, "Employee");
27. [Link] = [Link][0];
28. [Link]();
29.
30. }
31. }
626

List Controls:
In [Link], list controls are a type of server control used for
displaying lists of data. They allow you to present data in a
variety of formats, such as tables, lists, or dropdowns. Some
of the most commonly used list controls in [Link] include:
• ListBox: The ListBox control displays a list of items that
can be selected by the user. Multiple items can be
selected at once, and the control can be bound to a data
source to automatically populate the list.
• DropDownList: The DropDownList control displays a
list of items in a dropdown menu. Only one item can be
selected at a time, and the control can be bound to a data
source to automatically populate the list.
• CheckBoxList: The CheckBoxList control displays a list
of items with checkboxes next to them. Multiple items
can be selected at once, and the control can be bound to a
data source to automatically populate the list.
• RadioButtonList: The RadioButtonList control displays
a list of items with radio buttons next to them. Only one
item can be selected at a time, and the control can be
bound to a data source to automatically populate the list.
List controls in [Link] allow you to easily display and
manipulate data in your web application. They are
customizable and offer a range of features, such as data
binding, styling, and event handling, to help you create rich
and interactive user interfaces.

[Link] provides the following list controls.


627

• Drop-down list
• List box
• Radio button list
• Check box list
• Bulleted list
These controls display list of options to select. You can select
one or more options, the choice depends upon control. They
all derive from the [Link]
class

Some of the important common properties of list controls


are as follows:
• SelectedValue: Get the value of the selected item from
the dropdown list.
• SelectedIndex: Gets the index of the selected item from
the dropdown box.
• SelectedItem: Gets the text of selected item from the
list.
• Items: Gets the collection of items from the dropdown
list.
• DataTextField: Name of the data source field to supply
the text of the items. Generally this field came from the
datasource.
• DataValueField: Name of the data source field to supply
the value of the items. This is not visible field to list
controls, but you can use it in the code.
628

• DataSourceID: ID of the datasource control to provide


data.
There are several ways through which you can populate
these controls such as:
• By using data from database.
• Directly write code to add items.
• Add items through the items collection from property
window.
• Write HTML to populate these controls.
• Use inbuilt datasource controls.
DropDownList control
DropDownList control is used select single option from
multiple listed items.
Example
using System;
using [Link];
public partial class ListControls : [Link]
{
protected void Page_Load(object sender, EventArgs e)
{
if (! IsPostBack)
{
List<string> cityList = new List<string>();
[Link]("Pune");
[Link]("Kanpur");
[Link]("Jaipur");
[Link]("Delhi");
629

[Link]("Agra");
[Link] = cityList;
[Link]();
}
}
protected void
DropDownList1_SelectedIndexChanged(object sender,
EventArgs e)
{
[Link] = [Link];
}
}

Select the item from the DropDownList, the label control will
display the selected item. Please keep in mind that, you should
write code with association with IsPostBack property
otherwise you will get the first item of the DropDownList.

You can also add items directly to write HTML as follows:


<asp:DropDownList ID="DropDownList2" runat="server">
<asp:ListItem Value="1">India</asp:ListItem>
<asp:ListItem Value="2">USA</asp:ListItem>
<asp:ListItem Value="2">Australia</asp:ListItem>
<asp:ListItem Value="4">Canada</asp:ListItem>
<asp:ListItem Value="5">Newzealand</asp:ListItem>
</asp:DropDownList>

ListBox control
630

The ListBox control is similar to the DropDownList but main


difference is that you can select multiple items from ListBox
at a time. ListBox control has SelectionMode property that
enables you to select multiple items from ListBox control. By
default SelectionMode property is set as single. If you want to
select multiple items from the ListBox, then set
SelectionMode property value as Multiple and press Ctrl or
Shift key when clicking more than one list item.

The ListBox control also supports data binding. You can bind
the ListBox through coding with database or attach it with one
of the predefined DataSourceControl objects, which contains
the items to display in the control. DataTextField and
DataValueField properties are used to bind to the Text and
Value field in the data source.
Example
using System;
using [Link];
using [Link];
using [Link];
public partial class ListControls : [Link]
{
List<string> empList;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
empList = new List<string>();
[Link]("Raj");
631

[Link]("Rajesh");
[Link]("John");
[Link]("Elina");
[Link]("Samy");
[Link]("Reena");
[Link] = empList;
[Link]();
}
}

protected void Button1_Click(object sender, EventArgs e)


{
StringBuilder sb = new StringBuilder();
foreach(ListItem item in [Link])
{
if([Link])
{
[Link](item + "</br>");
}
}
[Link] = [Link]();
}
}

Execute the above program and select the items from ListBox.
Click on show button, you will get the selected items.
The ListBox control has a SelectedIndexChanged event
handler. If AutoPostBack property is set to true, then this
event is raised whenever you select new item from the List
control.
632

Tabular & Hierarchical Data Bound Controls:


The Hierarchy of Data Bound Controls
Data Bound controls are controls that are bound to data
sources. Traditionally the DataGrid is the principal data bound
control in [Link] 1.x. Though DataGrid is still supported,
[Link] 2.0 introduces three new controls—GridView,
FormView and DetailsView.
Unlike in [Link] 1.x, all controls descend from the
BaseDataBoundControl class. It has two basic child classes
DataBoundControl and HierarchicalDataBoundControl. While
TreeView and Menu are examples of the latter, AdRotator,
ListControls such as BulletedList, CheckboxList,
DropDownList, ListBox and RadioButtonList, and
CompositeDataBoundControls such as DetailsView,
FormsView and GridView are examples of the former.
633

All Data bound controls can be classified into Simple,


composite and hierarchical controls. The DataBoundControl
Base class defines the common characteristics of non-
hierarchical controls which share the same base class. It is
inherited from the WebControl and has all the visual and style
properties of the base class. Additionally it has infrastructural
properties such as Context, Page and AccessKey.
DataMember property of the control selects the list of data
that the control has to bind to when the DataSource contains
more than one list. DataSource indicates the source of the data
it has to bind to. It is imperative that the DataSource must be
an object (unlike [Link] 1.x) that implements the
IEnumerable or the IListSource interface. DataSourceId is the
ID of the data source object used to retrieve data.
The DataBoundControl class has only one method—the
DataBind method. This method is called when data has to be
pumped out of the data source. The internal implementation of
this method has been tweaked and modified to enhance
performance. It takes into account the implementation of the
IEnumerable based data sources but is more sophisticated in
execution as it implements the new interfaces and new data
source controls also.
Simple Data Bound Controls
List based user interface controls have been classified as
Simple Data bound controls. [Link] 2.0 has two simple
data bound controls—the AdRotator and the list control.
The AdRotator control retrieves information from a XML file
which contains the path to the distinctive image, the URL to
go to when the control is clicked and the frequency of the Ad.
634

Arbitrary data sources are supported by the control in


[Link] 2.0 and it is fully bound to the data source. This
control has additional capability of creating popup and pop
under ads apart from standard banners. It supports counters
for tracking purposes and updates the ad when the counter is
clicked. Each ad can be associated with a separate counter.
The BulletedList control is a new addition to list controls in
[Link]. It can be used to create a list of formatted list
items. Individual items can be specified by defining a ListItem
for each object. The bulleted lists are filled in from the data
source and receives the DataTable returned by a query. The
DataTextField property of the control selects the column to
show and the DisplayMode sets the display mode. The
Hyperlink mode links the page directly to an external URL
and click is handled by the browser. The LinkButton mode
click is handled by the [Link] runtime and fires a server
side event. The OnClick handler will have to be defined in
this instance. The Index property of the
BulletedListEventArgs class contains the base index of the
clicked item. The BulletStyle property controls the
customization of the bullet styles.
There is no change in the other list controls in [Link] 2.0.
Composite DataBound Controls
Two new base classes have been added to enhance the
Composite Data bound controls. The new CompositeControl
and CompositeDataBoundControl are separate classes with a
similar blueprint. The CompositeControl class addresses the
UI-based needs and CompositeDataBoundControl defines the
common foundation for all composite data bound controls.
635

The CompositeDataBoundControl is an abstract class that


declares and implements the Controls property. In [Link]
1.x the Controls property stores the references to child
controls. The CompositeDataBoundControl additionally
exposes the CreateChildControls property. It takes a Boolean
argument and behaves in accordance with the argument taken
to ignore or initialize the view state. In [Link] 2.0 the
developer has to only call the PerformDataBinding method
and all boilerplate tasks are performed and the implementation
of the CreateChildControls is called to implement the building
of the control tree. We shall see examples of the GridView,
the DetailsView and the FormView controls a little later in
this tutorial.
Hierarchical Data Bound Controls
The HierarchicalDataBoundControl class is the base class for
hierarchical data bound controls such as TreeView and Menu.
It is an abstract class but does not have any predefined
services. It behaves like a logical container for controls that
consume the hierarchical data.
The TreeView control displays a hierarchy of nodes. Each
node may contain child nodes. Parent nodes can be expanded
to display child nodes or collapsed. Checkboxes can be
displayed next to nodes or images from an imagelist control
can be displayed. Nodes can be programmatically selected or
cleared.
The key properties of the TreeView control are Nodes and
SelectedNodes. The Nodes property defines the top level
nodes in the TreeView. The SelectedNode property sets the
currently selected node.
636

The TreeView control binds to any data source object that


implements the IHierarchicalDataSource interface. It also
exposes a DataSource property of the type object which can
be assigned to an XmlDataDocument or to plain XML. By
default the nodes are bound to its own nodes to reflect the
name of the node rather than the attribute or the inner text.
The node to node association can be controlled by binding
parameters. The nodes can be bound to a data source field by
specifying tree node bindings. The TreeNodeBinding object
defines the relationship between each data item and the node
it is binding.
The Menu control is an end to end site navigation tool. It can
be bound to any data source and also supports explicit list of
items for simple cases. The menu items are stored in a
collection and the MenuItems collection property returns all
the child items of a given menu. A few static and dynamic
methods are supported by this class such as selected item,
submenus and mouse over items. Dynamic menus are
implemented using the Dynamic HTML object model.
In this section of the tutorial we have examined in some detail
the various kinds of Data Bound controls and listed out the
general features of each of these controls. In the following
sections we shall experiment with the implementation of these
controls on the web page of a Web application.
Tabular Databound Control:
Data Bound Controls areIn [Link], Tabular Data
Bound Controlsare :are controls that can be used to display
data in a tabular format (like a grid) and bind data from
various sources such as a database, an API, or any data
637

collection. These controls make it easier to manage, display,


and manipulate tabular data in your web applications. The
most commonly used tabular data bound controls in [Link]
are:
1. GridView
2. Repeater
3. DataList
4. ListView
Here's a brief overview of each control and how they are
typically used:
[Link]
• .The GridViewis one of the most commonly used
controls for displaying tabular data in [Link].
• It supports sorting, paging, editing, deleting, and
selecting operations on the data.
• You can bind a GridViewcontrol to a data source like a
DataTable, SQLDataSource, ObjectDataSource, or any
other data collection.
GridView Example:
as
Copy it
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="ProductID"
DataSourceID="SqlDataSource1">
638

<Columns>
<asp:BoundField DataField="ProductID"
HeaderText="Product ID" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName"
HeaderText="Product Name"
SortExpression="ProductName" />
<asp:BoundField DataField="Price" HeaderText="Price"
SortExpression="Price" />
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"


ConnectionString="your_connection_string"
SelectCommand="SELECT ProductID, ProductName,
Price FROM Products">
</asp:SqlDataSource>
2. Repeater
• isThe Repeateris a simpler control than the GridViewand
provides a higher degree of flexibility.
• , etc. ) .It allows you to customize the layout and the
rendering of data using templates (such as ItemTemplate,
HeaderTemplate, etc.).
• It doesn't provide built-in features like sorting, paging, or
editing, but it allows you to have complete control over
the display of data.
639

Repeater Example:
aspx
Copy it
<asp:Repeater ID="Repeater1" runat="server"
DataSourceID="SqlDataSource1">
<ItemTemplate>
<tr>
<td><%# Eval("ProductID") %></td>
<td><%# Eval("ProductName") %></td>
<td><%# Eval("Price") %></td>
</tr>
</ItemTemplate>
</asp:Repeater>
[Link]
• The DataListcontrol is similar to the Repeaterin that it
allows for customized data rendering. However, it also
supports features like alternating item styles (odd/even
rows).
• It provides more layout options, such as displaying items
in a list or grid view.
DataList Example:
aspx
Copy it
640

<asp:DataList ID="DataList1" runat="server"


DataSourceID="SqlDataSource1">
<ItemTemplate>
<tr>
<td><%# Eval("ProductID") %></td>
<td><%# Eval("ProductName") %></td>
<td><%# Eval("Price") %></td>
</tr>
</ItemTemplate>
</asp:DataList>
[Link]
• The ListViewcontrol is the most flexible and powerful
data-bound control among the four.
• , andIt allows for highly customizable layouts, including
different templates for different views like
ItemTemplate, EditItemTemplate, and
InsertItemTemplate.
• It supports paging, sorting, and templated layouts.
ListView Example:
aspx
Copy it
<asp:ListView ID="ListView1" runat="server"
DataSourceID="SqlDataSource1">
<ItemTemplate>
641

<tr>
<td><%# Eval("ProductID") %></td>
<td><%# Eval("ProductName") %></td>
<td><%# Eval("Price") %></td>
</tr>
</ItemTemplate>
</asp:ListView>
Differences:
• GridView : Offers built-in support for sorting, paging,
editing, and selecting. Ideal for scenarios where you need
a fully-featured grid view with minimal customizations.
• Repeater : Gives maximum flexibility in customizing
the HTML output but doesn't have built-in support for
features like paging or sorting.
• DataList : Offers more control over the layout compared
to the GridView and Repeater, with features like
alternating row styles.
• ListView : Most flexible of the data-bound controls,
used when you need maximum control over the layout
and functionality, including templates for editing and
inserting data.
642

STATE MANAGEMENT WEB SERVICES


View State:
A web application is stateless. That means that a new instance
of a page is created every time we make a request to the server
to get the page, and after the round trip, our page is lost
immediately. It only happens because of one server, all the
controls of the Web Page are created, and after the round trip,
the server destroys all the instances. So to retain the values of
the controls we use state management techniques.
State Management Techniques
They are classified into the following 2 categories.

What is View State?


View State is the method to preserve the Value of the Page
and Controls between round trips. It is a Page-Level State
Management technique. View State is turned on by default
and normally serializes the data in every control on the page
regardless of whether it is actually used during a post-back.
643

Now I am showing you an example of what the problem is


when we don't use view state.
Step 1. Open Visual Studio 2010.

Step 2. Then click on "New Project" > "Web" >"[Link]


Empty Web Application."
Step 3. Now click on Solution Explorer.
644

Step 4. Now right-click on the "ADD" > "New Item" > "Web
Form" and add the name of the Web Form just like I did in
[Link].
645

Step 5. After adding the [Link] you will see the


following code.
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="[Link]"
Inherits="view_state.WebForm6" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0


Transitional//EN"
"[Link]
[Link]">
646

<html xmlns="[Link]
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<p>
UserName: <asp:TextBox ID="TextBox1"
runat="server"></asp:TextBox>
<br />
Password: <asp:TextBox ID="TextBox2"
runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server"
onclick="Button1_Click" Text="Submit" />
<asp:Button ID="Button3" runat="server"
onclick="Button3_Click" Text="Restore" />
</p>
</form>
</body>
</html>
Markup
Copy
Now write the code as in the following.
647

// Declaration of 'a' and 'b'


public string a, b;

protected void Button1_Click(object sender, EventArgs e)


{
// TextBox1 and TextBox2 values are assigned to the
variables 'a' and 'b'
a = [Link];
b = [Link];

// After clicking on Button, TextBox values will be cleared


[Link] = [Link] = [Link];
}

protected void Button3_Click(object sender, EventArgs e)


{
// Values of variables 'a' and 'b' are assigned to TextBox1
and TextBox2
[Link] = a;
[Link] = b;
}
C#
Copy
648

Output

It only happens because all the controls are classes and on the
server, all the Control Objects are created and then after the
round trip, the Page is returned to the client's browser in
HTML format, and the objects are destroyed at the server.
After the Submit button is clicked, the value of the user name
and password is submitted to the server. We cannot restore the
value again because after the postback, the instance of the
control is destroyed, and on clicking the Restore Button, the
server takes a new request, and the server cannot restore the
value of the TextBox.
649

Features Of View State


These are the main features of the view state.
1. Retains the value of the Control after post-back without
using a session.
2. Stores the value of Pages and Control Properties defined
in the page.
3. Creates a custom View State Provider that lets you store
View State Information in a SQL Server Database or in
another data store.
Now, I am explaining the stored value in the View State, and
the remaining steps are the same as the previous ones.
Now write this code.
protected void Button1_Click(object sender, EventArgs e)
{
// Value of TextBox1 and TextBox2 is assigned to the
ViewState
ViewState["name"] = [Link];
ViewState["password"] = [Link];

// After clicking on Button, TextBox value will be cleared


[Link] = [Link] = [Link];
}

protected void Button3_Click(object sender, EventArgs e)


650

{
// If ViewState values are not null, assign them to
TextBoxes
if (ViewState["name"] != null)
{
[Link] = ViewState["name"].ToString();
}

if (ViewState["password"] != null)
{
[Link] = ViewState["password"].ToString();
}
}
C#
Copy
Output
651

After clicking on the Submit Button, the value of the user


name and password is submitted in View State, and the View
State stores the value of the user name and password during
post-back.
After clicking on the Restore Button, we can get the value
again. The Value must be retained during post-back, and the
values are stored into a base 64 encoded string, and this
information is then put into the View State Hidden Field.
Data Objects That Can be Stored in View state
1. String
2. Boolean Value
3. Array Object
4. Array List Object
5. Hash Table
6. Custom type Converters
Advantages of View State
1. Easy to Implement.
652

2. No server resources are required: The View State is


contained in a structure within the page load.
3. Enhanced security features: It can be encoded and
compressed or Unicode implementation.
Disadvantages of View State
1. Security Risk: The Information of View State can be
seen in the page output source directly. You can
manually encrypt and decrypt the contents of a Hidden
Field, but It requires extra coding. If security is a concern
then consider using a Server-Based state Mechanism so
that no sensitive information is sent to the client.
2. Performance: Performance is not good if we use a large
amount of data because View State is stored in the page
itself and storing a large value can cause the page to be
slow.
3. Device limitation: Mobile Devices might not have the
memory capacity to store a large amount of View State
data.
4. It can store values for the same page only.
When We Should Use View State
1. When the data to be stored is small.
2. Try to avoid secure data.
653

How to Enable and Disable View State


You can enable and disable View State for a single control as
well as at the page level. To turn off View State for a single
control, set the EnableViewState property of that control to
false.
[Link]=false;
C#
Copy
To turn off the View State for an entire page, we need to
setEnableViewState to false of the page directive, as shown
below.
<%PageLanguage="C#"EnableViewState="false";
C#
Copy
To enable the same, you need to use the same property just set
it to "True".
View State Security
654

View State Data is stored in the form of Base 64 encoding,


but it is not very secure. Anyone can easily break it. So there
are the following 2 options,
1. Using the MAC for Computing the View State Hash
Value
Generally, the larger MAC key is used to generate a
Hash Key. When the key is auto-generated, then
[Link] uses SHA-1 encoding to create a larger key.
Those keys must be the same for all the servers. If the
key is not the same and the page is posted back to a
different server than the one that created the page, then
the [Link] Page Framework raises an exception. We
can enable it by using.
<%PageLanguage="C#"EnableViewState="true"EnableView
StateMac="true";
C#
Copy
2. Encryption
By using MAC Encoding, we cannot prevent the viewing
of the data, so to prevent the viewing, we transmit the
page over SSL and encrypt the View State Data. To
encrypt the data, we have the ViewStateEncryptionMode
Property, and it has the following 3 options.
• Always: Encrypt the data Always.
• Never: Encrypt the data Never.
• Auto: Encrypt any Control request, especially for
Encryption
We can enable it by using.
655

1. <%PageLanguage="C#"EnableViewState="trueViewStat
eEncryptionMode="Always"

Session:
In [Link] session is a state that is used to store and retrieve
values of a user.
It helps to identify requests from the same browser during a
time period (session). It is used to store value for the
particular time session. By default, [Link] session state is
enabled for all [Link] applications.
PauseNext
Mute
Current Time 0:06
/
Duration 7:03
Loaded: 10.40%
Fullscreen
Each created session is stored
in SessionStateItemCollection object. We can get current
session value by using Session property of Page object. Let's
see an example, how to create an access session in [Link]
application.

[Link] Session Example


656

In the following example, we are creating a session and


storing user email. This example contains the following files.
// [Link]
1. <%@ Page Title="Home Page" Language="C#" AutoEv
entWireup="true" CodeBehind="[Link]"
2. Inherits="SessionExample._Default" %>
3. <head>
4. <style type="text/css">
5. .auto-style1 {
6. width: 100%;
7. }
8. .auto-style2 {
9. width: 105px;
10. }
11. </style>
12. </head>
13. <form id="form1" runat="server">
14. <p>Provide Following Details</p>
15. <table class="auto-style1">
16. <tr>
17. <td class="auto-style2">Email</td>
18. <td>
19. <asp:TextBox ID="email" runat="server"
TextMode="Email"></asp:TextBox>
657

20. </td>
21. </tr>
22. <tr>
23. <td class="auto-style2">Password</td>
24. <td>
25. <asp:TextBox ID="password" runat="ser
ver" TextMode="Password"></asp:TextBox>
26. </td>
27. </tr>
28. <tr>
29. <td class="auto-style2">฀</td>
30. <td>
31. <asp:Button ID="login" runat="server" T
ext="Login" OnClick="login_Click" />
32. </td>
33. </tr>
34. </table>
35. <br />
36. <asp:Label ID="Label3" runat="server"></asp:L
abel>
37. <br />
38. <asp:Label ID="Label4" runat="server"></asp:L
abel>
39. </form>
658

Code
// [Link]
1. using System;
2. using [Link];
3. namespace SessionExample
4. {
5. public partial class _Default : Page
6. {
7. protected void login_Click(object sender, EventAr
gs e)
8. {
9. if ([Link]=="qwe123")
10. {
11. // Storing email to Session variable
12. Session["email"] = [Link];
13. }
14. // Checking Session variable is not empty
15. if (Session["email"] != null)
16. {
17. // Displaying stored email
18. [Link] = "This email is stored to the
session.";
19. [Link] = Session["email"].ToString(
);
659

20. }
21. }
22. }
23. }
Output:
This application will store user email to the session when user
login.

It will show stored session value, user email.


660

Cookies:
Cookies is a small piece of information stored on the client
machine. This file is located on client machines
"C:\Document and Settings\Currently_Login user\Cookie"
path. It is used to store user preference information like
Username, Password, City, PhoneNo, etc, on client machines.
We need to import a namespace called
[Link] before we use cookie.
Type of Cookies
1. Persist Cookie - A cookie that doesn't have expired
time is called a Persist Cookie
2. Non-Persist Cookie - A cookie which has expired time is
called a Non-Persist Cookie
How to create a cookie?
It is really easy to create a cookie in [Link] with the help of a
Response object or HttpCookie.
Example 1
HttpCookie userInfo = new HttpCookie("userInfo");
userInfo["UserName"] = "Annathurai";
userInfo["UserColor"] = "Black";
[Link](new TimeSpan(0, 1, 0));
[Link](userInfo);
C#
Copy
Example 2
661

[Link]["userName"].Value = "Annathurai";
[Link]["userColor"].Value = "Black";
C#
Copy
How to retrieve from cookie?
It is an easy way to retrieve cookie value from cookies with
the help of Request object.
Example 1
string User_Name = [Link];
string User_Color = [Link];
User_Name = [Link]["userName"].Value;
User_Color = [Link]["userColor"].Value;
C#
Copy
Example 2
string User_name = [Link];
string User_color = [Link];
HttpCookie reqCookies = [Link]["userInfo"];
if (reqCookies != null)
{
User_name = reqCookies["UserName"].ToString();
User_color = reqCookies["UserColor"].ToString();
}
662

C#
Copy
When we make a request from the client to web server, the
web server processes the request and gives a lot of
information with big pockets, which will have Header
information, Metadata, cookies, etc., Then respose object can
do all the things with browser.
Cookie's common property
1. Domain => This is used to associate cookies to domain.
2. Secure => We can enable secure cookie to set
true(HTTPs).
3. Value => We can manipulate individual cookie.
4. Values => We can manipulate cookies with key/value
pair.
5. Expires => This is used to set expire date for the cookies.
Advantages of Cookie
1. It has clear text so the user can read it.
2. We can store user preference information on the client
machine.
3. It is an easy way to maintain.
4. Fast accessing.
Disadvantages of Cookie
1. If the user clears the cookie information, we can't get it
back.
2. No security.
663

3. Each request will have cookie information with page.


How to clear the cookie information?
1. We can clear cookie information from client machine on
cookie folder
2. To set expires to cookie object
[Link] = [Link](1);
C#
Copy
It will clear the cookie within one hour.

Application:
[Link] Application state is a server side state management
technique.
Application state is a global storage mechanism that used to
stored data on the server and shared for all users, means data
stored in Application state is common for all user. Data from
Application state can be accessible anywhere in the
application. Application state is based on the
[Link] class.
The application state used same way as session state, but
session state is specific for a single user session, where as
application state common for all users of [Link] application.
Syntax of Application State
Store information in application state
• Application[“name”] = “Meera Academy”;
664

Retrieve information from application state


• string str = Application[“name”].ToString();
Example of Application State in [Link]
Generally we use application state for calculate how many
times a given page has been visited by various clients.
Design web page in visual studio as shows in below figure.

Application State
management in [Link]
Here, we calculate total visit of uses visited web page by
clicking “Click to Visit” button.
C# Code for Example
protected void btnvisit_Click(object sender, EventArgs e)
{
int count = 0;

if (Application["Visit"] != null)
{
count =
Convert.ToInt32(Application["Visit"].ToString());
665

count = count + 1;
Application["Visit"] = count;
[Link] = "Total Visit = " + [Link]();

}
Output of Example

Application State Example in [Link]


Here, above output screen we use different browser for visit
same page. The result counter value stored in Application
object so it would be changed simultaneously for both
visitors.
In above case some time too many users click button at the
same time, that time result wont be accurate. This situation
known as dead lock. To avoid dead lock we use Lock() and
UnLock() in application state.
Lock() and UnLock() in Application State
protected void btnvisit_Click(object sender, EventArgs e)
666

{
[Link]();
int cnt = 0;

if (Application["Visit"] != null)
{
cnt =
Convert.ToInt32(Application["Visit"].ToString());
}

cnt = cnt + 1;
Application["Visit"] = cnt;

[Link]();
[Link] = "Total Visit = " + [Link]();

Session State Example in [Link]


Now, do above same example using Session state.
667

Session State Example in [Link]


C# code for above example
protected void btnvisit_Click(object sender, EventArgs e)
{
int cnt = 0;

if (Session["Visit"] != null)
{
cnt = Convert.ToInt32(Session["Visit"].ToString());
}
cnt = cnt + 1;
Session["Visit"] = cnt;

[Link] = "Total Visit = " + [Link]();

}
668

Hidden Fields:
HiddenField, as name implies, is hidden. This is non visual
control in [Link] where you can save the value. This is one
of the types of client-side state management tools. It stores the
value between the roundtrip. Anyone can see HiddenField
details by simply viewing the source of document.
HiddenFields are not encrypted or protected and can be
changed by anyone. However, from a security point of view,
this is not suggested. [Link] uses HiddenField control for
managing the ViewState. So, don’t store any important or
confidential data like password and credit card details with
this control.
<asp:HiddenFieldID="HiddenField1" runat="server" />
[Link] (C#)
Copy
Use of HiddenField
We developers mostly do not show an ID value of table like
ProductID, MemberID because users are not concerned with
this kind of data. We store that information in HiddenFields
and complete our process very easily.
Events of HiddenFields
As a control, it should have events. HiddenFields has the
following events.
EVENT TYPE DESCRIPTION

Occurs when Server Control binds to a data


DataBinding
source.
669

Occurs when Server Control is released from


Disposed
the memory.

Init Occurs when Server Control is initialized.

Occurs when server control get loaded on the


Load
page.

PreRender Occurs before Rendering the page.

Occurs when Server Control is unloaded


UnLoad
from memory.

Occurs when the value gets changed between


ValueChanged
the round-trip (postback).
ValueChanged event is server-side control. This event gets
executed when the value of HiddenField gets changed
between postback to the Server.
Nowadays, people avoid using server side ValueChanged
Event because all these things are possible through JavaScript
or jQuery very easily.
Store the value in HiddenField
<asp:HiddenFieldID="hdnfldCurrentDateTime"
runat="server" />
[Link] (C#)
Copy
Set the value of HiddenField in code behind
protected void Page_Load(object sender, EventArgs e) {
670

[Link] =
[Link]();
}
C#
Copy
Retrieve the value from HiddenField
[Link] =
[Link]([Link]);
C#
Copy
Step by step implementation
Create a new [Link] Website project called
“HiddenFieldExample”.

Right click on project and select Add-->Add New Item and


select Web Form.
671

Add a new Web Form called "[Link]".

Now, drag and drop the HiddenField Control on the page.


672

By default, the HiddenField control looks like this.


<asp:HiddenFieldID="HiddenField1" runat="server" />
[Link] (C#)
Copy
[Link] Code
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="[Link]" Inherits="_Default" %>
<!DOCTYP Ehtml>
<html xmlns="[Link]
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
673

<asp:HiddenFieldID="hdnfldCurrentDateTime"
runat="server" />
<asp:LabelID="lblCurrentDateTime"
runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
[Link] (C#)
Copy
[Link] Code
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
public partial class_Default: [Link] {
protected void Page_Load(object sender, EventArgs e) {
[Link] =
[Link]();
[Link] =
[Link]([Link]);
}
674

}
C#
Copy
Output

Authentication & Authorization:


Authorization determines what each application or service
user is allowed to access. Authorization and authentication
often work together, but these are two separate processes.
Before being authorized to access and perform specific
actions, the user must undergo authentication (a mechanism
for proving a user’s identity).
When logging into a system, a user must provide credentials
like a username and password to authenticate. Next, the
authorization process grants rights. For example, an
administrative user can create a document library to add, edit,
and delete documents, while a non-administrative user can
only read documents in the library.
[Link] Core provides a simple, declarative policy-based
authorization model. The authorization mechanism is
expressed in requirements, while handlers evaluate a user’s
claims against these requirements. It allows setting imperative
checks according to simple policies that evaluate the user
identity and the requested resource’s properties.
675

1. Simple Authorization in [Link] Core


AuthorizeAttribute and its associated parameters manage
authorization in [Link] Core. The [Authorize] attribute,
when applied to a controller, Razor, or action page, restricts
access to such users who have been authorized. The following
code restricts unauthorized users from accessing the
Account_Controller:
[Authorize]

public class Account_Controller : Controlle


{
public Result_of_Action Signin()
{
}
public Result_of_Action Signout()
{
}
}

To assign authorization to a specific action instead of a


controller, use the AuthorizeAttribute attribute.

public class Account_Controller : Controller


{
676

public Result_of_Action Signin()


{
}
[Authorize]
public Result_of_Action Signout()
{
}
}

The Signout operation is now protected and only accessible to


authenticated users. The AllowAnonymous attribute can
enable access to specific operations, even to users who have
not yet authenticated. For example:

[Authorize]

public class Account_Controller : Controller


{
[AllowAnonymous]
public Result_of_Action Signin()
{
}
public Result_of_Action Signout()
{
677

}
}
It would restrict access to the Account_Controller to
authorized users, excluding the Signin function, which may be
performed by anyone irrespective of their authentication.
2. Role-Based Authorization in [Link] Core
Role-based authorization allows you to assign and control
roles granularly. Once you create an identity in [Link]
Core, it can belong to one or several roles. For example, one
user identity can belong to the user and administrator roles,
while another belongs only to the user role.
You can create and manage roles according to the underlying
store of the authorization process. However, roles are exposed
to developers only through the IsInRole method of the
ClaimsPrincipal class.
Roles and claims
A role can be a claim, but not all claims can be roles. The
identity issuer determines whether a role can be a set of users
allowed to apply claims for group members. Claims provide
information about an individual user. Using roles to add
claims to users can create confusion between users and their
claims, which is why SPA templates are not designed around
roles.
You can register role-based authorization services in
[Link] by calling AddRoles with the role type in the
application’s identity configuration. Here’s an example of
using IdentityRole as the role type:
[Link]<IdentityUser>( ... )
678

.AddRoles<IdentityRole>()
...
Declarative role-based authorization checks
A role-based authorization check is declarative, allowing you
to specify the roles a user must belong to access a requested
resource. You can apply role-based authorization checks to
Razor Pages, controllers, and actions within controllers.
However, you can’t apply them at the Razor Page handler
level – only to the Page.
The following code limits access to actions on the
AdministrationController to any user belonging to the
administrator role:
[Authorize(Roles = "Administrator")]

public class AdministrationController : Controller


{
public IActionResult Index() =>
Content("Administrator");
}
3. Claims-Based Authorization in [Link] Core
[Link] Core lets a trusted part assign one of several claims
to a single identity. A claim represents a name-value pair that
indicates what a subject is rather than what a subject can do.
Claims-based authorization allows access to a resource
according to the claim’s value. An identity can include several
679

claims with different values and several claims of the same


type.
A claim-based authorization check is declarative. You can
apply it to Razor Pages, controllers, and actions in controllers.
You can’t apply it at the Razor Page handler level – only to
pages.
4. Policy-Based Authorization in [Link] Core
The policy-based authorization mechanism in [Link] Core
is intended to isolate authorization and application
functionality. A policy is a structure of predetermined
constraints that the user must meet.
The most fundamental policy is that the user must be
authorized, while role association is one of the most used
requirements. Another commonly used requirement is having
a specific claim or a claim with a specific value.
Requirements are user identity assertions that attempt to
access valid methods. For example, use the following code to
implement a policies object:
var policies = new AuthorizationPolicyBuilder()

.AddAuthenticationSchemes("Cookie, Bearer")

.RequireAuthenticatedUser()

.RequireRole("Admin")
680

.RequireClaim("editor", "contents") .RequireClaim("level",


"junior")

.Build();
Requirements are gathered by the builder object, which then
constructs the policies instance using several extension
methods. As shown above, requirements affect authentication
status, roles, schemes, and any combination of claims read
from the authentication cookie or bearer token.

Developing Secure Web Services:


If we want to secure our web method from an unauthenticated
client request then there are many ways to do this but there is
also a way to create a web service and create all the web
methods for Authentication first so we can do that with a
custom SOAP header.

We embed the SOAP header into our message and validate its
contents on the server.

If the SOAP header validates successfully then the web server


sends the web service response to the client application.

We need to use [SoapHeader] on every [WebMethod] and for


this attribute we must use a namespace “using
[Link];”.

So let's have an example.


681

Step 1

Open Visual Studio then select File -> New -> Web site.

Step 2

Add a Web Service File to the web site.

Provide the name to the Web Service File that will add a
682

.asmx file to the web site project.

Then delete the existing class file that is provided by the web
service template.

And add a new Class File to create [WebMethod] and


[WebService].
683

With a specified class name.

Step 3

Now use the namespace first that is required.


684

And create any Test [WebMethod].

Step 4

Now edit and set the CodeBehind and class the property in the
.asmx file with the name of the web service class.

Step 5

Now right-click on your Web Service (.asmx) file and view in


it in a browser to test [WebMethod].
685

Then you will see the name of your web methods list on the
page like.

Click the name of Method to test.


686

Enter the UserName Parameter's value like “Nitin Pandit”.


Now click on the Invoke button to see the result of your web
method.

Then the result will show on the page in XML format.

Step 6

The methods are working perfectly but I need to define the


Authentication before calling every [WebMethod].

So add a class file to create user credentials.


687

I added a class to my web service with UserDetails and I also


declared the IsValid() function that returns a bool value after
checking that the user details are vailed for login or not to be
authenticated.

Code
1. using System;
688

2. using [Link];
3. using [Link];
4. using [Link];
5.
6. public class UserDetails : [Link]
[Link]
7. {
8. public string userName { get; set; }
9. public string password { get; set; }
10.
11.
12. public bool IsValid()
13. {
14. //Write the logic to Check the User Details Fro
m DataBase
15. //i can chek with some hardcode details UserN
ame=Nitin and Password=Pandit
16. return [Link] == "Nitin" && [Link]
word == "Pandit";
17. //it'll check the details and will return true or fa
lse
18. }
19. }
689

Step 7

Now use this class UserDetails on [SoapHeader] to


authentication before checking the method calling.

Code
1. using System;
2. using [Link];
3. using [Link];
4. using [Link];
5. using [Link];
6. using [Link];
7.
690

8. [WebService]
9. public class MyServiceClass
10. {
11. public UserDetails User;
12. [WebMethod]
13. [SoapHeader("User", Required = true)]
14. public string SayHello(string userName)
15. {
16. if (User != null)
17. {
18. if ([Link]())
19. return [Link]("Hello...{0} {1} ☺ "
, userName,
20. [Link]("tt") == "AM
" ? " good morning " : " good evening ");
21. else
22. return "Error in authentication";
23. }
24. else
25. {
26. return "Error in authentication";
27. }
28. }
691

29. }
Step 8

Now build the Web Service and view it in the browser again
and click on the web method name and pass the parameter
value.

Click on Invoke.

The output will be “Error in authentication” because we never


assign the UserDetails class object before calling the
WebMethod. That's why the server returns an Error Message
from the WebMethod.

Step 9

Now create a web application or any other application to test


this web method with SoapHeader attribute.
692

Right-click on the solution file and add a new web site.

Then provide the name to the web application where you can't
use this service.
693

Step 10

<="" proxy="" side="" client="" from="" namespace=""


local="" the="" write="" and="" site="" new="" to=""
reference="" service="" web="" add="" style="margin: 0px;
padding: 0px; box-sizing: border-box; font-family: "Plus
Jakarta Sans", sans-serif; color: rgb(154, 185, 220); font-size:
14px; font-style: normal; font-variant-ligatures: normal; font-
variant-caps: normal; font-weight: 300; letter-spacing:
normal; orphans: 2; text-align: start; text-indent: 0px; text-
transform: none; widows: 2; word-spacing: 0px; -webkit-text-
stroke-width: 0px; white-space: normal; background-color:
rgb(9, 18, 39); text-decoration-thickness: initial; text-
decoration-style: initial; text-decoration-color: initial;">
694

Add a new Web Form and then create just 2 TextBoxes and a
button to call and test the web service from the application.

Create a UI for the page.


695

And write all the requirements.

Step 11

Now at the last page run in the web browser.


696

With the correct information I will call it and the output is


Hello…Nitin evening ;)

The result is returned and here is an error in authentication


because of the wrong password so we can set the
authentication for our Web Methods.
697

You might also like