when a request reaches iis

53
When a request reaches IIS For example user might type some thing like this in the browser: http://YourHostName/DirectoryName/FileName.aspx The task of the web server is to accept the http request and to serve the requested page as HTTP Response. Now IIS is going to decide how it is going to handle the request. The IIS decision is based upon the file extension. If the extension is asp i.e. Classic ASP then it will route the request to asp.dll. But if it is an ASP.NET request then IIS will route it to ASP.NET Engine (if you go to IIS, right click on default website, go to home directory and then to configurations, you can see the extensions and there executable paths). Now we will examine how ASP.NET Engine will process the request. ASP.NET engine is often called as asp.net http pipeline. Incoming request will pass through number of Http Modules before reaching Http Handler. Http Modules are nothing but classes which can inspect the incoming request and make decisions which may affect the internal flow of the request... After passing through the Http modules it has now reached the Http Handler which will produce the output. I will explain only one Http Handler here. When a request comes for an asp.net page with .aspx extension the request is handed off to the ASP.NET engine. The request then moves through the modules. The request is then routed to the PageHandlerFactory, since in the machine.config's < httpHandler > section we have the mapping: < httpHandlers > < add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerF actory" /> < /httpHandlers > Now PageHandlerF actory will provide an instance of Http Handler and it tries to find the compiled class that represents the ASP .NET Web page that is being requested. When the ASP.NET Web page is first visited, the ASP.NET engine creates a class that derives from the System.W eb.UI.Page class. This dynamically created class is then compiled. The Page class implements IHttphandler interface which indicates that it uses an http handler . PageHandlerF actory sees whether the compiled version for the requested class (page) exists. If not it will create the class and compiles it. Some method of this class is invoked (I am not sure which one) and it will create a completer html code for that particular page. It is sent back through the Http Modules as response and it is rendered in the page. That's it. You are viewing your requested page... Introduction When reques t come from client to the server a lot of oper ation is perfo rmed before sending response to the client. This is all about how IIS Process the request . Here I am not going to describe the Page Life Cycle and there events, this article is all about the operat ion of IIS Level. Befor e we start with the actual detai ls, let’s star t from

Upload: gayams123

Post on 08-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 153

When a request reaches IIS

For example user might type some thing like this in the browser

httpYourHostNameDirectoryNameFileNameaspx

The task of the web server is to accept the http request and to serve the requestedpage as HTTP Response Now IIS is going to decide how it is going to handle the

request The IIS decision is based upon the file extension If the extension is asp ieClassic ASP then it will route the request to aspdll But if it is an ASPNET requestthen IIS will route it to ASPNET Engine (if you go to IIS right click on default

website go to home directory and then to configurations you can see the extensionsand there executable paths)

Now we will examine how ASPNET Engine will process the request ASPNET engine

is often called as aspnet http pipeline Incoming request will pass through number of Http Modules before reaching Http Handler Http Modules are nothing but classes

which can inspect the incoming request and make decisions which may affect theinternal flow of the request

After passing through the Http modules it has now reached the Http Handler whichwill produce the output I will explain only one Http Handler here

When a request comes for an aspnet page with aspx extension the request is

handed off to the ASPNET engine The request then moves through the modulesThe request is then routed to the PageHandlerFactory since in the machineconfigs

lt httpHandler gt section we have the mapping

lt httpHandlers gtlt add verb= path=aspx type=SystemWebUIPageHandlerFactory gt

lt httpHandlers gt

Now PageHandlerFactory will provide an instance of Http Handler and it tries to

find the compiled class that represents the ASPNET Web page that is beingrequested When the ASPNET Web page is first visited the ASPNET engine

creates a class that derives from the SystemWebUIPage class This

dynamically created class is then compiled The Page class implementsIHttphandler interface which indicates that it uses an http handler

PageHandlerFactory sees whether the compiled version for the requested class(page) exists If not it will create the class and compiles it

Some method of this class is invoked (I am not sure which one) and it will create a

completer html code for that particular page It is sent back through the Http

Modules as response and it is rendered in the page Thats it You are viewingyour requested page

Introduction

When request come from client to the server a lot of operation is performed before

sending response to the client This is all about how IIS Process the request Here I

am not going to describe the Page Life Cycle and there events this article is all aboutthe operation of IIS Level Before we start with the actual details letrsquos start from

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 253

the beginning so that each and everyone understand its details easily Pleaseprovide your valuable feedback and suggestion to improve this article

What is Web Server

When we run our ASPNET Web Application from visual studio IDE VS Integrated

ASPNET Engine is responsible to execute all kind of aspnet requests andresponses The process name is WebDevWebServerExe which actually takw

care of all request and response of an web application which is running from VisualStudio IDE

Now the name ldquoWeb Serverrdquo come into picture when we want to host the applicationon a centralized location and wanted to access from many locations Web server is

responsible for handle all the requests that are coming from clients process themand provide the responses

What is IIS

IIS (Internet Information Server) is one of the most powerful web servers fromMicrosoft that is used to host your ASPNET Web application IIS has its own

ASPNET Process Engine to handle the ASPNET request So when a request comes

from client to server IIS takes that request and process it and send response backto clients

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 353

Request Processing

Hope till now itrsquos clear to you that what is Web server and IIS is and what is the useof them Now letrsquos have a look how they do things internally Before we move ahead

you have to know about two main concepts

1 Worker Process

2 Application Pool

Worker Process Worker Process (w3wpexe) runs the ASPNet application in IISThis process is responsible to manage all the request and response that are coming

from client system All the ASPNet functionality runs under the scope of worker

process When a request comes to the server from a client worker process isresponsible to generate the request and response In a single word we can say

worker process is the heart of ASPNET Web Application which runs on IIS

Application Pool Application pool is the container of worker process Application

pools is used to separate sets of IIS worker processes that share the sameconfiguration Application pools enables a better security reliability and availability

for any web application The worker process serves as the process boundary thatseparates each application pool so that when one worker process or application is

having an issue or recycles other applications or worker processes are not affected

This makes sure that a particular web application doesnt not impact other webapplication as they they are configured into different application pools

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 453

Application Pool with multiple worker process is called ldquoWeb Gardenrdquo

Now I have covered all the basic stuff like Web server Application Pool Workerprocess Now letrsquos have look how IIS process the request when a new request comes

up from client

If we look into the IIS 60 Architecture we can divided them into Two Layer

1 Kernel Mode2 User Mode

Now Kernel mode is introduced with IIS 60 which contains the HTTPSYS Sowhenever a request comes from Client to Server it will hit HTTPSYS First

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 553

Now HTTPSYS is Responsible for pass the request to particular Application poolNow here is one question How HTTPSYS comes to know where to send the

request This is not a random pickup Whenever we creates a new Application Poolthe ID of the Application Pool is being generated and itrsquos registered with the

HTTPSYS So whenever HTTPSYS Received the request from any web application itchecks for the Application Pool and based on the application pool it send the request

So this was the first steps of IIS Request Processing

Till now Client Requested for some information and request came to the Kernel levelof IIS means at HTTPSYS HTTPSYS has been identified the name of the application

pool where to send Now letrsquos see how this request moves from HTTPSYS to

Application Pool

In User Level of IIS we have Web Admin Services (WAS) which takes the requestfrom HTTPSYS and pass it to the respective application pool

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 653

When Application pool receive the request it simply pass the request to workerprocess (w3wpexe) The worker process ldquow3wpexerdquo looks up the URL of therequest in order to load the correct ISAPI extension ISAPI extensions are the IIS

way to handle requests for different resources Once ASPNET is installed it installsits own ISAPI extension (aspnet_isapidll) and adds the mapping into IIS

Note Sometimes if we install IIS after installing aspnet we need to register the

extension with IIS using aspnet_regiis command

When Worker process loads the aspnet_isapidll it start an HTTPRuntime which isthe entry point of an application HTTPRuntime is a class which calls the

ProcessRequest method to start Processing

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 753

When this methods called a new instance of HTTPContext is been created Which

is accessible using HTTPContextCurrent

+ Properties This object still remains alive during life time of object request Using

HttpContextCurrent we can access some other objects like Request ResponseSession etc

After that HttpRuntime load an HttpApplication object with the help of HttpApplicationFactory class Each and every request should pass through the

corresponding HTTPModule to reach to HTTPHandler this list of module areconfigured by the HTTPApplication

Now the concept comes called ldquoHTTPPipelinerdquo It is called a pipeline because it

contains a set of HttpModules ( For Both Webconfig and Machineconfig level) thatintercept the request on its way to the HttpHandler HTTPModules are classes that

have access to the incoming request We can also create our own HTTPModule if we

need to handle anything during upcoming request and response

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 853

HTTP Handlers are the endpoints in the HTTP pipeline All request that are passing

through the HTTPModule should reached to HTTPHandler Then HTTP Handlergenerates the output for the requested resource So when we requesting for any

aspx web pages it returns the corresponding HTML output

All the request now passes from httpModule to respective HTTPHandler then

method and the ASPNET Page life cycle starts This ends the IIS Request processingand start the ASPNET Page Lifecycle

Conclusion

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 953

When client request for some information from a web server request first reaches toHTTPSYS of IIS HTTPSYS then send the request to respective Application Pool

Application Pool then forward the request to worker process to load the ISAPIExtension which will create an HTTPRuntime Object to Process the request via

HTTPModule and HTTPHanlder After that the ASPNET Page LifeCycle events starts

One of the very common question in any dot net interview is aboult explaining ASPNET page lifecycle

ASPNET page life cycle is not very tough to know but in many books I have seen it is written insuch a manner that it seems to be very complicated

In this article I will try to explain the page life cycle as simple as possible

How it all begins

A user sits at her browser and types in a URL A web page appears with text imagesbuttonsand so forth She fills in a text box and clicks a button New data appears in response How doesthis work

When an ASPNET page is requested from the server the server loads the page into server memory processes the page sends the page to the user and then unloads it from memoryFrom the beginning of the life cycle to the end the goal is to render appropriate HTML to therequesting browser At each step methods and events are available that allow you to override thedefault behavior or add your own programmatic enhancements

There are two slightly different sequences in the life cycle one for the first time a page is loadedand a second when the page reloads itself in a postback

During the first page load the life cycle consists of the following steps

1 A request for the page is made from a browser to the web server The ASPNET Frameworkfirst determines whether the page already exists in a cache (a section of memory specificallyreserved for recently used items) If so the page is retrieved and returned to the browser and weare done If not then the actual page life cycle starts at this point

2 During the Start phase the postback mode is determined If the page was requested by adifferent page then it was not a postback If the page was returned to the server for processingand redisplay then it is a postbackThe IsPostBack and PreviousPage properties are set accordingly The Request andResponse properties of the page along with a number of other properties are alsoset

3 The Page Initialization phase contains two events often handled by your codePreInit and InitIf you do not handle these explicitly yourself ASPNET will perform the default behavior on your behalf

During the PreInit event the target device is determined before the page is initialized the master page is set the control tree is built and the controls are assigned unique IDs which are madeavailable to your code Personalization and themes are loaded and applied to the page in thisstep

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1053

PreInit is the first event in the life cycle that can be trapped and handled That is this is the firstevent that you can write your own code for to change the default behavior of initializing the page

4 During the Init event control properties are read or initialized If this is a postback it isimportant to realize that the controls wonrsquot reflect any changes to the page made before thepostbackthat happens in the PreRender phase They will contain values specified in themarkup file

5 During the Load event all the control properties are set View state information is availableand controls in the pagersquos control hierarchy can be accessed The load phase is routinelymodified in a Page_Load method

6 During the Validation phase the Validate method is called on all the validation controls on thepage The IsValid property is set for all those controls and for the page as a whole

7 During the Rendering phase personalization control and view state is saved Each control onthe page is called in succession to render itself to the browser that is to compose itself intoHTML that is included in the pagersquos Response property

It is very common to handle the PreRender event with a Page_PreRender method typicallywhen you must take some action based on the final value of some other control on the pageDuring the Render event the HTML is actuallygenerated and sent to the requesting pagealthough this event is rarely handled unless you are developing custom controls

8 Unload is the last event of the life cycle It gives you an opportunity to do any final cleanup(ie closing open files and releasing references to expensive resources such as databaseconnections)

During postback the life cycle is the same as during the first load except for the following

1 During the Load phase after initialization is complete the view state and the control state areloaded and applied as necessary

2 After the Validation phase completes postback data is processed Control event handlers arenow executed

This is important control event handlers such as a Button Click are not called until after thePage Initialization and Load events are handled

The following are the various stages a page goes through

Page Request

The request page is either parsed or compiled or fetched from the cache

Start

Page properties like the Request and Response are set The type of request is determined

specifically whether it is a new Request or it is a PostBack Culturing properties are also

determined via the pages ICulture property

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1153

Page Initialization

All the controls on the given page are initialized with a UniqueID (please donrsquot confused

this with the ID property as the UnqiueID is a unique hierarchicial identifier whichincludes the server

controlrsquos naming container) Theming is also applied at this stage

Load

If the current request is a PostBack the data from the viewstate and control state is

loaded to the appropriate properties of the controls

Validation

The Validate method of all the validator controls are fired which in turn sets the Boolean

property IsValid of the controls

Postback Event Handling

If the current request is a PostBack all event handlers are called

Rendering

ViewState data is saved for all the controls that have enabled viewstate The Render

method for all the controls is fired which writes its output to the OutputStream via a text

writer

Unload

Once the page has been rendered and sent the Pagersquos properties are unloaded (cleanup

time)

So know you have a better understanding of the various stages of a ASPNET pages lifecycle you should be aware that within each of the above stages there are events that you

can hook into so that your code is fired at the exact time that you want it to

Event Wire-up is another important concept to understand So Event wire-up is where

ASPNET looks for methods that match a naming convention (eg Page_Load Page_Initetc) and these methods are automatically fired at the appropriate event There is a page

level attribute AutoEventWireup that can be set to either true or false to enable this

behaviour

Below are some of the more popular events that you should understand as you will mostlikely be interested in them

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1253

PreInit

You can use this event to

Create recreate dynamic controls

Set a master page or theme dynamically

Access profile properties

Init

Used to read or initialize your control properties

InitComplete

Used when you need to access your properties after they have been initialized

PreLoad

Used when you need to process things before the Load event has been fired

Load

The Pagersquos OnLoad method and all of its child controlrsquos OnLoad method are firedrecursively This event is used to set properties and make database connections

Control Events

Control specific events are handled at this stage eg Click eventrsquos for the button control

LoadComplete

This stage is for when you need to access controls that have been properly loaded

PreRender

Can be used to make any lsquolast chancersquo changes to the controls before they are rendered

SaveStateComplete

This event is used for things that require view state to be saved yet not making anychanges to the controls themselves

Render

The page object calls this method on all of the controls so all the controls are written andsent to the browser

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1353

Unload

All the controls UnLoad method are fired followed by the pages UnLoad event (bottom-

up) This stage is used for closing database connections closing open files etc

It is import to understand that each server control has its very own life cycle but they arefired recursively so things may not occur at the time you think they do (they occur in

reverse order) What this means is that some events fire from the bottom up like the Init

event while others load from the top-down like the Load event

Purpose

State management is the process by which you maintain state and page information

over multiple requests for the same or different pages

Types of State Management

There are 2 types State Management

1 Client ndash Side State Management This stores information on the clients computer by embedding the information into a

Web page a uniform resource locator(url) or a cookie The techniques available tostore the state information at the client end are listed down below

a View State ndash AspNet uses View State to track the values in the Controls You can

add custom values to the view state It is used by the Aspnet page framework toautomatically save the values of the page and of each control just prior to rendering

to the page When the page is posted one of the first tasks performed by page

processing is to restore view state

b Control State ndash If you create a custom control that requires view state to work

properly you should use control state to ensure other developers donrsquot break yourcontrol by disabling view state

c Hidden fields ndash Like view state hidden fields store data in an HTML form without

displaying it in the users browser The data is available only when the form isprocessed

d Cookies ndash Cookies store a value in the users browser that the browser sends with

every page request to the same server Cookies are the best way to store state datathat must be available for multiple Web pages on a web site

e Query Strings - Query strings store values in the URL that are visible to the userUse query strings when you want a user to be able to e-mail or instant message

state data with a URL

2 Server ndash Side State Management

a Application State - Application State information is available to all pagesregardless of which user requests a page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1453

b Session State ndash Session State information is available to all pages opened by auser during a single visit

Both application state and session state information is lost when the application

restarts To persist user data between application restarts you can store it usingprofile properties

Implementation Procedure

Client ndash Side State Management

View State

The ViewState property provides a dictionary object for retaining values betweenmultiple requests for the same page When an ASPNET page is processed the

current state of the page and controls is hashed into a string and saved in the pageas a hidden field If the data is too long for a single field then ASPNET performs

view state chunking (new in ASPNET 20) to split it across multiple hidden fields

The following code sample demonstrates how view state adds data as a hidden formwithin a Web pagersquos HTML

ltinput type=hidden name=__VIEWSTATE id=__VIEWSTATErdquovalue=wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHnrt75XFpMGnqjqHlH66cdw== gt

Encrypting of the View State You can enable view state encryption to make it more

difficult for attackers and malicious users to directly read view state informationThough this adds processing overhead to the Web server it supports in storing

confidential information in view state To configure view state encryption for an

application does the following

ltConfigurationgt

ltsystemwebgt

ltpages viewStateEncryptionMode=Alwaysgt

ltsystemwebgt

ltconfigurationgt

Alternatively you can enable view state encryption for a specific page by setting thevalue in the page directive as the following sample demonstrates

lt Page Language=C AutoEventWireup=true CodeFile=DefaultaspxcsInherits=_Default ViewStateEncryptionMode=Alwaysgt

View State is enabled by default but if you can disable it by setting the

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1553

EnableViewState property for each web control to false This reduces the serverprocessing time and decreases page size

Reading and Writing Custom View State DataIf you have a value that yoursquod like to keep track of while the user is visiting a single

ASPNET Web page adding a custom value to ViewState is the most efficient andsecure way to do that However ViewState is lost if the user visits a different Web

page so it is useful only for temporarily storing valuesExample Determine the time of last visit to the page

Check if View State object exists and display it if it does

If (ViewState [lastVisit]= null)

Label1Text = (string)ViewState[lastVisit] else

Label1Text = lastVisit ViewState not defined

Define the ViewState object for the next page viewViewStateAdd(lastVisit DateTimeNowToString())

Control State If you create a custom control that requires ViewState you can use

the ControlState property to store state information for your control ControlStateallows you to persist property information that is specific to a control and cannot be

turned off like the ViewState property To use control state in a custom control your

control must override the OnInit method and call the Register-RequiresControlStatemethod during initialization and then override the SaveControl-State and

LoadControlState methods

Hidden fields ViewState stores information in the Web page using hidden fieldsHidden fields are sent back to the server when the user submits a form however

the information is never displayed by the Web browser (unless the user chooses toview the page source) ASPNET allows you to create your own custom hidden fields

and store values that are submitted with other form data A HiddenField controlstores a single variable in its Value property and must be explicitly added to the

page You can use hidden fields only to store information for a single page so it isnot useful for storing session data If you use hidden fields you must submit your

pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which

happens if the user clicks a link) Unlike view state data hidden fields have no built-in compression encryption hashing or chunking so users can view or modify data

stored in hidden fields

Cookies Web applications can store small pieces of data in the clientrsquos Web browserby using cookies A cookie is a small amount of data that is stored either in a text file

on the client file system (if the cookie is persistent) or in memory in the clientbrowser session (if the cookie is temporary) The most common use of cookies is to

identify a single user as he or she visits multiple Web pages

Reading and Writing Cookies

A Web application creates a cookie by sending it to the client as a header in an HTTP

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1653

response The Web browser then submits the same cookie to the server with everynew request

Create a cookie -gt add a value to the ResponseCookies HttpCookieCollectionRead a cookie -gt read values in RequestCookies

Example

Check if cookie exists and display it if it does

if (RequestCookies[lastVisit] = null) Encode the cookie in case thecookie contains client-side script Label1Text =ServerHtmlEncode(RequestCookies[lastVisit]Value)

else Label1Text = No value defined

Define the cookie for the next visit ResponseCookies[lastVisit]Value =DateTimeNowToString()ResponseCookies[lastVisit]Expires =DateTimeNowAddDays(1)

If you do not define the Expires property the browser stores it in memory and the

cookie is lost if the user closes his or her browser

To delete a cookie overwrite the cookie and set an expiration date in the past Youcanrsquot directly delete cookies because they are stored on the clientrsquos computer

Controlling the Cookie Scope By default browsers wonrsquot send a cookie to a Web sitewith a different hostname You can control a cookiersquos scope to either limit the scope

to a specific folder on the Web server or expand the scope to any server in a domainTo limit the scope of a cookie to a folder set the Path property as the following

example demonstrates

Example

ResponseCookies[lastVisit]Path = Application1

Through this the scope is limited to the ldquoApplication1rdquo folder that is the browser

submits the cookie to any page with in this folder and not to pages in other folderseven if the folder is in the same server We can expand the scope to a particular

domain using the following statementExample

ResponseCookies[ldquolastVisitrdquo]Domain = ldquoContosordquo

Storing Multiple Values in a CookieThough it depends on the browser you typically canrsquot store more than 20 cookies

per site and each cookie can be a maximum of 4 KB in length To work around the

20-cookie limit you can store multiple values in a cookie as the following codedemonstratesExample

ResponseCookies[info][visit]Value = DateTimeNowToString()

ResponseCookies[info][firstName]Value = Tony

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 253

the beginning so that each and everyone understand its details easily Pleaseprovide your valuable feedback and suggestion to improve this article

What is Web Server

When we run our ASPNET Web Application from visual studio IDE VS Integrated

ASPNET Engine is responsible to execute all kind of aspnet requests andresponses The process name is WebDevWebServerExe which actually takw

care of all request and response of an web application which is running from VisualStudio IDE

Now the name ldquoWeb Serverrdquo come into picture when we want to host the applicationon a centralized location and wanted to access from many locations Web server is

responsible for handle all the requests that are coming from clients process themand provide the responses

What is IIS

IIS (Internet Information Server) is one of the most powerful web servers fromMicrosoft that is used to host your ASPNET Web application IIS has its own

ASPNET Process Engine to handle the ASPNET request So when a request comes

from client to server IIS takes that request and process it and send response backto clients

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 353

Request Processing

Hope till now itrsquos clear to you that what is Web server and IIS is and what is the useof them Now letrsquos have a look how they do things internally Before we move ahead

you have to know about two main concepts

1 Worker Process

2 Application Pool

Worker Process Worker Process (w3wpexe) runs the ASPNet application in IISThis process is responsible to manage all the request and response that are coming

from client system All the ASPNet functionality runs under the scope of worker

process When a request comes to the server from a client worker process isresponsible to generate the request and response In a single word we can say

worker process is the heart of ASPNET Web Application which runs on IIS

Application Pool Application pool is the container of worker process Application

pools is used to separate sets of IIS worker processes that share the sameconfiguration Application pools enables a better security reliability and availability

for any web application The worker process serves as the process boundary thatseparates each application pool so that when one worker process or application is

having an issue or recycles other applications or worker processes are not affected

This makes sure that a particular web application doesnt not impact other webapplication as they they are configured into different application pools

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 453

Application Pool with multiple worker process is called ldquoWeb Gardenrdquo

Now I have covered all the basic stuff like Web server Application Pool Workerprocess Now letrsquos have look how IIS process the request when a new request comes

up from client

If we look into the IIS 60 Architecture we can divided them into Two Layer

1 Kernel Mode2 User Mode

Now Kernel mode is introduced with IIS 60 which contains the HTTPSYS Sowhenever a request comes from Client to Server it will hit HTTPSYS First

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 553

Now HTTPSYS is Responsible for pass the request to particular Application poolNow here is one question How HTTPSYS comes to know where to send the

request This is not a random pickup Whenever we creates a new Application Poolthe ID of the Application Pool is being generated and itrsquos registered with the

HTTPSYS So whenever HTTPSYS Received the request from any web application itchecks for the Application Pool and based on the application pool it send the request

So this was the first steps of IIS Request Processing

Till now Client Requested for some information and request came to the Kernel levelof IIS means at HTTPSYS HTTPSYS has been identified the name of the application

pool where to send Now letrsquos see how this request moves from HTTPSYS to

Application Pool

In User Level of IIS we have Web Admin Services (WAS) which takes the requestfrom HTTPSYS and pass it to the respective application pool

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 653

When Application pool receive the request it simply pass the request to workerprocess (w3wpexe) The worker process ldquow3wpexerdquo looks up the URL of therequest in order to load the correct ISAPI extension ISAPI extensions are the IIS

way to handle requests for different resources Once ASPNET is installed it installsits own ISAPI extension (aspnet_isapidll) and adds the mapping into IIS

Note Sometimes if we install IIS after installing aspnet we need to register the

extension with IIS using aspnet_regiis command

When Worker process loads the aspnet_isapidll it start an HTTPRuntime which isthe entry point of an application HTTPRuntime is a class which calls the

ProcessRequest method to start Processing

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 753

When this methods called a new instance of HTTPContext is been created Which

is accessible using HTTPContextCurrent

+ Properties This object still remains alive during life time of object request Using

HttpContextCurrent we can access some other objects like Request ResponseSession etc

After that HttpRuntime load an HttpApplication object with the help of HttpApplicationFactory class Each and every request should pass through the

corresponding HTTPModule to reach to HTTPHandler this list of module areconfigured by the HTTPApplication

Now the concept comes called ldquoHTTPPipelinerdquo It is called a pipeline because it

contains a set of HttpModules ( For Both Webconfig and Machineconfig level) thatintercept the request on its way to the HttpHandler HTTPModules are classes that

have access to the incoming request We can also create our own HTTPModule if we

need to handle anything during upcoming request and response

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 853

HTTP Handlers are the endpoints in the HTTP pipeline All request that are passing

through the HTTPModule should reached to HTTPHandler Then HTTP Handlergenerates the output for the requested resource So when we requesting for any

aspx web pages it returns the corresponding HTML output

All the request now passes from httpModule to respective HTTPHandler then

method and the ASPNET Page life cycle starts This ends the IIS Request processingand start the ASPNET Page Lifecycle

Conclusion

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 953

When client request for some information from a web server request first reaches toHTTPSYS of IIS HTTPSYS then send the request to respective Application Pool

Application Pool then forward the request to worker process to load the ISAPIExtension which will create an HTTPRuntime Object to Process the request via

HTTPModule and HTTPHanlder After that the ASPNET Page LifeCycle events starts

One of the very common question in any dot net interview is aboult explaining ASPNET page lifecycle

ASPNET page life cycle is not very tough to know but in many books I have seen it is written insuch a manner that it seems to be very complicated

In this article I will try to explain the page life cycle as simple as possible

How it all begins

A user sits at her browser and types in a URL A web page appears with text imagesbuttonsand so forth She fills in a text box and clicks a button New data appears in response How doesthis work

When an ASPNET page is requested from the server the server loads the page into server memory processes the page sends the page to the user and then unloads it from memoryFrom the beginning of the life cycle to the end the goal is to render appropriate HTML to therequesting browser At each step methods and events are available that allow you to override thedefault behavior or add your own programmatic enhancements

There are two slightly different sequences in the life cycle one for the first time a page is loadedand a second when the page reloads itself in a postback

During the first page load the life cycle consists of the following steps

1 A request for the page is made from a browser to the web server The ASPNET Frameworkfirst determines whether the page already exists in a cache (a section of memory specificallyreserved for recently used items) If so the page is retrieved and returned to the browser and weare done If not then the actual page life cycle starts at this point

2 During the Start phase the postback mode is determined If the page was requested by adifferent page then it was not a postback If the page was returned to the server for processingand redisplay then it is a postbackThe IsPostBack and PreviousPage properties are set accordingly The Request andResponse properties of the page along with a number of other properties are alsoset

3 The Page Initialization phase contains two events often handled by your codePreInit and InitIf you do not handle these explicitly yourself ASPNET will perform the default behavior on your behalf

During the PreInit event the target device is determined before the page is initialized the master page is set the control tree is built and the controls are assigned unique IDs which are madeavailable to your code Personalization and themes are loaded and applied to the page in thisstep

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1053

PreInit is the first event in the life cycle that can be trapped and handled That is this is the firstevent that you can write your own code for to change the default behavior of initializing the page

4 During the Init event control properties are read or initialized If this is a postback it isimportant to realize that the controls wonrsquot reflect any changes to the page made before thepostbackthat happens in the PreRender phase They will contain values specified in themarkup file

5 During the Load event all the control properties are set View state information is availableand controls in the pagersquos control hierarchy can be accessed The load phase is routinelymodified in a Page_Load method

6 During the Validation phase the Validate method is called on all the validation controls on thepage The IsValid property is set for all those controls and for the page as a whole

7 During the Rendering phase personalization control and view state is saved Each control onthe page is called in succession to render itself to the browser that is to compose itself intoHTML that is included in the pagersquos Response property

It is very common to handle the PreRender event with a Page_PreRender method typicallywhen you must take some action based on the final value of some other control on the pageDuring the Render event the HTML is actuallygenerated and sent to the requesting pagealthough this event is rarely handled unless you are developing custom controls

8 Unload is the last event of the life cycle It gives you an opportunity to do any final cleanup(ie closing open files and releasing references to expensive resources such as databaseconnections)

During postback the life cycle is the same as during the first load except for the following

1 During the Load phase after initialization is complete the view state and the control state areloaded and applied as necessary

2 After the Validation phase completes postback data is processed Control event handlers arenow executed

This is important control event handlers such as a Button Click are not called until after thePage Initialization and Load events are handled

The following are the various stages a page goes through

Page Request

The request page is either parsed or compiled or fetched from the cache

Start

Page properties like the Request and Response are set The type of request is determined

specifically whether it is a new Request or it is a PostBack Culturing properties are also

determined via the pages ICulture property

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1153

Page Initialization

All the controls on the given page are initialized with a UniqueID (please donrsquot confused

this with the ID property as the UnqiueID is a unique hierarchicial identifier whichincludes the server

controlrsquos naming container) Theming is also applied at this stage

Load

If the current request is a PostBack the data from the viewstate and control state is

loaded to the appropriate properties of the controls

Validation

The Validate method of all the validator controls are fired which in turn sets the Boolean

property IsValid of the controls

Postback Event Handling

If the current request is a PostBack all event handlers are called

Rendering

ViewState data is saved for all the controls that have enabled viewstate The Render

method for all the controls is fired which writes its output to the OutputStream via a text

writer

Unload

Once the page has been rendered and sent the Pagersquos properties are unloaded (cleanup

time)

So know you have a better understanding of the various stages of a ASPNET pages lifecycle you should be aware that within each of the above stages there are events that you

can hook into so that your code is fired at the exact time that you want it to

Event Wire-up is another important concept to understand So Event wire-up is where

ASPNET looks for methods that match a naming convention (eg Page_Load Page_Initetc) and these methods are automatically fired at the appropriate event There is a page

level attribute AutoEventWireup that can be set to either true or false to enable this

behaviour

Below are some of the more popular events that you should understand as you will mostlikely be interested in them

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1253

PreInit

You can use this event to

Create recreate dynamic controls

Set a master page or theme dynamically

Access profile properties

Init

Used to read or initialize your control properties

InitComplete

Used when you need to access your properties after they have been initialized

PreLoad

Used when you need to process things before the Load event has been fired

Load

The Pagersquos OnLoad method and all of its child controlrsquos OnLoad method are firedrecursively This event is used to set properties and make database connections

Control Events

Control specific events are handled at this stage eg Click eventrsquos for the button control

LoadComplete

This stage is for when you need to access controls that have been properly loaded

PreRender

Can be used to make any lsquolast chancersquo changes to the controls before they are rendered

SaveStateComplete

This event is used for things that require view state to be saved yet not making anychanges to the controls themselves

Render

The page object calls this method on all of the controls so all the controls are written andsent to the browser

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1353

Unload

All the controls UnLoad method are fired followed by the pages UnLoad event (bottom-

up) This stage is used for closing database connections closing open files etc

It is import to understand that each server control has its very own life cycle but they arefired recursively so things may not occur at the time you think they do (they occur in

reverse order) What this means is that some events fire from the bottom up like the Init

event while others load from the top-down like the Load event

Purpose

State management is the process by which you maintain state and page information

over multiple requests for the same or different pages

Types of State Management

There are 2 types State Management

1 Client ndash Side State Management This stores information on the clients computer by embedding the information into a

Web page a uniform resource locator(url) or a cookie The techniques available tostore the state information at the client end are listed down below

a View State ndash AspNet uses View State to track the values in the Controls You can

add custom values to the view state It is used by the Aspnet page framework toautomatically save the values of the page and of each control just prior to rendering

to the page When the page is posted one of the first tasks performed by page

processing is to restore view state

b Control State ndash If you create a custom control that requires view state to work

properly you should use control state to ensure other developers donrsquot break yourcontrol by disabling view state

c Hidden fields ndash Like view state hidden fields store data in an HTML form without

displaying it in the users browser The data is available only when the form isprocessed

d Cookies ndash Cookies store a value in the users browser that the browser sends with

every page request to the same server Cookies are the best way to store state datathat must be available for multiple Web pages on a web site

e Query Strings - Query strings store values in the URL that are visible to the userUse query strings when you want a user to be able to e-mail or instant message

state data with a URL

2 Server ndash Side State Management

a Application State - Application State information is available to all pagesregardless of which user requests a page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1453

b Session State ndash Session State information is available to all pages opened by auser during a single visit

Both application state and session state information is lost when the application

restarts To persist user data between application restarts you can store it usingprofile properties

Implementation Procedure

Client ndash Side State Management

View State

The ViewState property provides a dictionary object for retaining values betweenmultiple requests for the same page When an ASPNET page is processed the

current state of the page and controls is hashed into a string and saved in the pageas a hidden field If the data is too long for a single field then ASPNET performs

view state chunking (new in ASPNET 20) to split it across multiple hidden fields

The following code sample demonstrates how view state adds data as a hidden formwithin a Web pagersquos HTML

ltinput type=hidden name=__VIEWSTATE id=__VIEWSTATErdquovalue=wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHnrt75XFpMGnqjqHlH66cdw== gt

Encrypting of the View State You can enable view state encryption to make it more

difficult for attackers and malicious users to directly read view state informationThough this adds processing overhead to the Web server it supports in storing

confidential information in view state To configure view state encryption for an

application does the following

ltConfigurationgt

ltsystemwebgt

ltpages viewStateEncryptionMode=Alwaysgt

ltsystemwebgt

ltconfigurationgt

Alternatively you can enable view state encryption for a specific page by setting thevalue in the page directive as the following sample demonstrates

lt Page Language=C AutoEventWireup=true CodeFile=DefaultaspxcsInherits=_Default ViewStateEncryptionMode=Alwaysgt

View State is enabled by default but if you can disable it by setting the

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1553

EnableViewState property for each web control to false This reduces the serverprocessing time and decreases page size

Reading and Writing Custom View State DataIf you have a value that yoursquod like to keep track of while the user is visiting a single

ASPNET Web page adding a custom value to ViewState is the most efficient andsecure way to do that However ViewState is lost if the user visits a different Web

page so it is useful only for temporarily storing valuesExample Determine the time of last visit to the page

Check if View State object exists and display it if it does

If (ViewState [lastVisit]= null)

Label1Text = (string)ViewState[lastVisit] else

Label1Text = lastVisit ViewState not defined

Define the ViewState object for the next page viewViewStateAdd(lastVisit DateTimeNowToString())

Control State If you create a custom control that requires ViewState you can use

the ControlState property to store state information for your control ControlStateallows you to persist property information that is specific to a control and cannot be

turned off like the ViewState property To use control state in a custom control your

control must override the OnInit method and call the Register-RequiresControlStatemethod during initialization and then override the SaveControl-State and

LoadControlState methods

Hidden fields ViewState stores information in the Web page using hidden fieldsHidden fields are sent back to the server when the user submits a form however

the information is never displayed by the Web browser (unless the user chooses toview the page source) ASPNET allows you to create your own custom hidden fields

and store values that are submitted with other form data A HiddenField controlstores a single variable in its Value property and must be explicitly added to the

page You can use hidden fields only to store information for a single page so it isnot useful for storing session data If you use hidden fields you must submit your

pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which

happens if the user clicks a link) Unlike view state data hidden fields have no built-in compression encryption hashing or chunking so users can view or modify data

stored in hidden fields

Cookies Web applications can store small pieces of data in the clientrsquos Web browserby using cookies A cookie is a small amount of data that is stored either in a text file

on the client file system (if the cookie is persistent) or in memory in the clientbrowser session (if the cookie is temporary) The most common use of cookies is to

identify a single user as he or she visits multiple Web pages

Reading and Writing Cookies

A Web application creates a cookie by sending it to the client as a header in an HTTP

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1653

response The Web browser then submits the same cookie to the server with everynew request

Create a cookie -gt add a value to the ResponseCookies HttpCookieCollectionRead a cookie -gt read values in RequestCookies

Example

Check if cookie exists and display it if it does

if (RequestCookies[lastVisit] = null) Encode the cookie in case thecookie contains client-side script Label1Text =ServerHtmlEncode(RequestCookies[lastVisit]Value)

else Label1Text = No value defined

Define the cookie for the next visit ResponseCookies[lastVisit]Value =DateTimeNowToString()ResponseCookies[lastVisit]Expires =DateTimeNowAddDays(1)

If you do not define the Expires property the browser stores it in memory and the

cookie is lost if the user closes his or her browser

To delete a cookie overwrite the cookie and set an expiration date in the past Youcanrsquot directly delete cookies because they are stored on the clientrsquos computer

Controlling the Cookie Scope By default browsers wonrsquot send a cookie to a Web sitewith a different hostname You can control a cookiersquos scope to either limit the scope

to a specific folder on the Web server or expand the scope to any server in a domainTo limit the scope of a cookie to a folder set the Path property as the following

example demonstrates

Example

ResponseCookies[lastVisit]Path = Application1

Through this the scope is limited to the ldquoApplication1rdquo folder that is the browser

submits the cookie to any page with in this folder and not to pages in other folderseven if the folder is in the same server We can expand the scope to a particular

domain using the following statementExample

ResponseCookies[ldquolastVisitrdquo]Domain = ldquoContosordquo

Storing Multiple Values in a CookieThough it depends on the browser you typically canrsquot store more than 20 cookies

per site and each cookie can be a maximum of 4 KB in length To work around the

20-cookie limit you can store multiple values in a cookie as the following codedemonstratesExample

ResponseCookies[info][visit]Value = DateTimeNowToString()

ResponseCookies[info][firstName]Value = Tony

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 353

Request Processing

Hope till now itrsquos clear to you that what is Web server and IIS is and what is the useof them Now letrsquos have a look how they do things internally Before we move ahead

you have to know about two main concepts

1 Worker Process

2 Application Pool

Worker Process Worker Process (w3wpexe) runs the ASPNet application in IISThis process is responsible to manage all the request and response that are coming

from client system All the ASPNet functionality runs under the scope of worker

process When a request comes to the server from a client worker process isresponsible to generate the request and response In a single word we can say

worker process is the heart of ASPNET Web Application which runs on IIS

Application Pool Application pool is the container of worker process Application

pools is used to separate sets of IIS worker processes that share the sameconfiguration Application pools enables a better security reliability and availability

for any web application The worker process serves as the process boundary thatseparates each application pool so that when one worker process or application is

having an issue or recycles other applications or worker processes are not affected

This makes sure that a particular web application doesnt not impact other webapplication as they they are configured into different application pools

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 453

Application Pool with multiple worker process is called ldquoWeb Gardenrdquo

Now I have covered all the basic stuff like Web server Application Pool Workerprocess Now letrsquos have look how IIS process the request when a new request comes

up from client

If we look into the IIS 60 Architecture we can divided them into Two Layer

1 Kernel Mode2 User Mode

Now Kernel mode is introduced with IIS 60 which contains the HTTPSYS Sowhenever a request comes from Client to Server it will hit HTTPSYS First

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 553

Now HTTPSYS is Responsible for pass the request to particular Application poolNow here is one question How HTTPSYS comes to know where to send the

request This is not a random pickup Whenever we creates a new Application Poolthe ID of the Application Pool is being generated and itrsquos registered with the

HTTPSYS So whenever HTTPSYS Received the request from any web application itchecks for the Application Pool and based on the application pool it send the request

So this was the first steps of IIS Request Processing

Till now Client Requested for some information and request came to the Kernel levelof IIS means at HTTPSYS HTTPSYS has been identified the name of the application

pool where to send Now letrsquos see how this request moves from HTTPSYS to

Application Pool

In User Level of IIS we have Web Admin Services (WAS) which takes the requestfrom HTTPSYS and pass it to the respective application pool

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 653

When Application pool receive the request it simply pass the request to workerprocess (w3wpexe) The worker process ldquow3wpexerdquo looks up the URL of therequest in order to load the correct ISAPI extension ISAPI extensions are the IIS

way to handle requests for different resources Once ASPNET is installed it installsits own ISAPI extension (aspnet_isapidll) and adds the mapping into IIS

Note Sometimes if we install IIS after installing aspnet we need to register the

extension with IIS using aspnet_regiis command

When Worker process loads the aspnet_isapidll it start an HTTPRuntime which isthe entry point of an application HTTPRuntime is a class which calls the

ProcessRequest method to start Processing

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 753

When this methods called a new instance of HTTPContext is been created Which

is accessible using HTTPContextCurrent

+ Properties This object still remains alive during life time of object request Using

HttpContextCurrent we can access some other objects like Request ResponseSession etc

After that HttpRuntime load an HttpApplication object with the help of HttpApplicationFactory class Each and every request should pass through the

corresponding HTTPModule to reach to HTTPHandler this list of module areconfigured by the HTTPApplication

Now the concept comes called ldquoHTTPPipelinerdquo It is called a pipeline because it

contains a set of HttpModules ( For Both Webconfig and Machineconfig level) thatintercept the request on its way to the HttpHandler HTTPModules are classes that

have access to the incoming request We can also create our own HTTPModule if we

need to handle anything during upcoming request and response

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 853

HTTP Handlers are the endpoints in the HTTP pipeline All request that are passing

through the HTTPModule should reached to HTTPHandler Then HTTP Handlergenerates the output for the requested resource So when we requesting for any

aspx web pages it returns the corresponding HTML output

All the request now passes from httpModule to respective HTTPHandler then

method and the ASPNET Page life cycle starts This ends the IIS Request processingand start the ASPNET Page Lifecycle

Conclusion

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 953

When client request for some information from a web server request first reaches toHTTPSYS of IIS HTTPSYS then send the request to respective Application Pool

Application Pool then forward the request to worker process to load the ISAPIExtension which will create an HTTPRuntime Object to Process the request via

HTTPModule and HTTPHanlder After that the ASPNET Page LifeCycle events starts

One of the very common question in any dot net interview is aboult explaining ASPNET page lifecycle

ASPNET page life cycle is not very tough to know but in many books I have seen it is written insuch a manner that it seems to be very complicated

In this article I will try to explain the page life cycle as simple as possible

How it all begins

A user sits at her browser and types in a URL A web page appears with text imagesbuttonsand so forth She fills in a text box and clicks a button New data appears in response How doesthis work

When an ASPNET page is requested from the server the server loads the page into server memory processes the page sends the page to the user and then unloads it from memoryFrom the beginning of the life cycle to the end the goal is to render appropriate HTML to therequesting browser At each step methods and events are available that allow you to override thedefault behavior or add your own programmatic enhancements

There are two slightly different sequences in the life cycle one for the first time a page is loadedand a second when the page reloads itself in a postback

During the first page load the life cycle consists of the following steps

1 A request for the page is made from a browser to the web server The ASPNET Frameworkfirst determines whether the page already exists in a cache (a section of memory specificallyreserved for recently used items) If so the page is retrieved and returned to the browser and weare done If not then the actual page life cycle starts at this point

2 During the Start phase the postback mode is determined If the page was requested by adifferent page then it was not a postback If the page was returned to the server for processingand redisplay then it is a postbackThe IsPostBack and PreviousPage properties are set accordingly The Request andResponse properties of the page along with a number of other properties are alsoset

3 The Page Initialization phase contains two events often handled by your codePreInit and InitIf you do not handle these explicitly yourself ASPNET will perform the default behavior on your behalf

During the PreInit event the target device is determined before the page is initialized the master page is set the control tree is built and the controls are assigned unique IDs which are madeavailable to your code Personalization and themes are loaded and applied to the page in thisstep

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1053

PreInit is the first event in the life cycle that can be trapped and handled That is this is the firstevent that you can write your own code for to change the default behavior of initializing the page

4 During the Init event control properties are read or initialized If this is a postback it isimportant to realize that the controls wonrsquot reflect any changes to the page made before thepostbackthat happens in the PreRender phase They will contain values specified in themarkup file

5 During the Load event all the control properties are set View state information is availableand controls in the pagersquos control hierarchy can be accessed The load phase is routinelymodified in a Page_Load method

6 During the Validation phase the Validate method is called on all the validation controls on thepage The IsValid property is set for all those controls and for the page as a whole

7 During the Rendering phase personalization control and view state is saved Each control onthe page is called in succession to render itself to the browser that is to compose itself intoHTML that is included in the pagersquos Response property

It is very common to handle the PreRender event with a Page_PreRender method typicallywhen you must take some action based on the final value of some other control on the pageDuring the Render event the HTML is actuallygenerated and sent to the requesting pagealthough this event is rarely handled unless you are developing custom controls

8 Unload is the last event of the life cycle It gives you an opportunity to do any final cleanup(ie closing open files and releasing references to expensive resources such as databaseconnections)

During postback the life cycle is the same as during the first load except for the following

1 During the Load phase after initialization is complete the view state and the control state areloaded and applied as necessary

2 After the Validation phase completes postback data is processed Control event handlers arenow executed

This is important control event handlers such as a Button Click are not called until after thePage Initialization and Load events are handled

The following are the various stages a page goes through

Page Request

The request page is either parsed or compiled or fetched from the cache

Start

Page properties like the Request and Response are set The type of request is determined

specifically whether it is a new Request or it is a PostBack Culturing properties are also

determined via the pages ICulture property

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1153

Page Initialization

All the controls on the given page are initialized with a UniqueID (please donrsquot confused

this with the ID property as the UnqiueID is a unique hierarchicial identifier whichincludes the server

controlrsquos naming container) Theming is also applied at this stage

Load

If the current request is a PostBack the data from the viewstate and control state is

loaded to the appropriate properties of the controls

Validation

The Validate method of all the validator controls are fired which in turn sets the Boolean

property IsValid of the controls

Postback Event Handling

If the current request is a PostBack all event handlers are called

Rendering

ViewState data is saved for all the controls that have enabled viewstate The Render

method for all the controls is fired which writes its output to the OutputStream via a text

writer

Unload

Once the page has been rendered and sent the Pagersquos properties are unloaded (cleanup

time)

So know you have a better understanding of the various stages of a ASPNET pages lifecycle you should be aware that within each of the above stages there are events that you

can hook into so that your code is fired at the exact time that you want it to

Event Wire-up is another important concept to understand So Event wire-up is where

ASPNET looks for methods that match a naming convention (eg Page_Load Page_Initetc) and these methods are automatically fired at the appropriate event There is a page

level attribute AutoEventWireup that can be set to either true or false to enable this

behaviour

Below are some of the more popular events that you should understand as you will mostlikely be interested in them

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1253

PreInit

You can use this event to

Create recreate dynamic controls

Set a master page or theme dynamically

Access profile properties

Init

Used to read or initialize your control properties

InitComplete

Used when you need to access your properties after they have been initialized

PreLoad

Used when you need to process things before the Load event has been fired

Load

The Pagersquos OnLoad method and all of its child controlrsquos OnLoad method are firedrecursively This event is used to set properties and make database connections

Control Events

Control specific events are handled at this stage eg Click eventrsquos for the button control

LoadComplete

This stage is for when you need to access controls that have been properly loaded

PreRender

Can be used to make any lsquolast chancersquo changes to the controls before they are rendered

SaveStateComplete

This event is used for things that require view state to be saved yet not making anychanges to the controls themselves

Render

The page object calls this method on all of the controls so all the controls are written andsent to the browser

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1353

Unload

All the controls UnLoad method are fired followed by the pages UnLoad event (bottom-

up) This stage is used for closing database connections closing open files etc

It is import to understand that each server control has its very own life cycle but they arefired recursively so things may not occur at the time you think they do (they occur in

reverse order) What this means is that some events fire from the bottom up like the Init

event while others load from the top-down like the Load event

Purpose

State management is the process by which you maintain state and page information

over multiple requests for the same or different pages

Types of State Management

There are 2 types State Management

1 Client ndash Side State Management This stores information on the clients computer by embedding the information into a

Web page a uniform resource locator(url) or a cookie The techniques available tostore the state information at the client end are listed down below

a View State ndash AspNet uses View State to track the values in the Controls You can

add custom values to the view state It is used by the Aspnet page framework toautomatically save the values of the page and of each control just prior to rendering

to the page When the page is posted one of the first tasks performed by page

processing is to restore view state

b Control State ndash If you create a custom control that requires view state to work

properly you should use control state to ensure other developers donrsquot break yourcontrol by disabling view state

c Hidden fields ndash Like view state hidden fields store data in an HTML form without

displaying it in the users browser The data is available only when the form isprocessed

d Cookies ndash Cookies store a value in the users browser that the browser sends with

every page request to the same server Cookies are the best way to store state datathat must be available for multiple Web pages on a web site

e Query Strings - Query strings store values in the URL that are visible to the userUse query strings when you want a user to be able to e-mail or instant message

state data with a URL

2 Server ndash Side State Management

a Application State - Application State information is available to all pagesregardless of which user requests a page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1453

b Session State ndash Session State information is available to all pages opened by auser during a single visit

Both application state and session state information is lost when the application

restarts To persist user data between application restarts you can store it usingprofile properties

Implementation Procedure

Client ndash Side State Management

View State

The ViewState property provides a dictionary object for retaining values betweenmultiple requests for the same page When an ASPNET page is processed the

current state of the page and controls is hashed into a string and saved in the pageas a hidden field If the data is too long for a single field then ASPNET performs

view state chunking (new in ASPNET 20) to split it across multiple hidden fields

The following code sample demonstrates how view state adds data as a hidden formwithin a Web pagersquos HTML

ltinput type=hidden name=__VIEWSTATE id=__VIEWSTATErdquovalue=wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHnrt75XFpMGnqjqHlH66cdw== gt

Encrypting of the View State You can enable view state encryption to make it more

difficult for attackers and malicious users to directly read view state informationThough this adds processing overhead to the Web server it supports in storing

confidential information in view state To configure view state encryption for an

application does the following

ltConfigurationgt

ltsystemwebgt

ltpages viewStateEncryptionMode=Alwaysgt

ltsystemwebgt

ltconfigurationgt

Alternatively you can enable view state encryption for a specific page by setting thevalue in the page directive as the following sample demonstrates

lt Page Language=C AutoEventWireup=true CodeFile=DefaultaspxcsInherits=_Default ViewStateEncryptionMode=Alwaysgt

View State is enabled by default but if you can disable it by setting the

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1553

EnableViewState property for each web control to false This reduces the serverprocessing time and decreases page size

Reading and Writing Custom View State DataIf you have a value that yoursquod like to keep track of while the user is visiting a single

ASPNET Web page adding a custom value to ViewState is the most efficient andsecure way to do that However ViewState is lost if the user visits a different Web

page so it is useful only for temporarily storing valuesExample Determine the time of last visit to the page

Check if View State object exists and display it if it does

If (ViewState [lastVisit]= null)

Label1Text = (string)ViewState[lastVisit] else

Label1Text = lastVisit ViewState not defined

Define the ViewState object for the next page viewViewStateAdd(lastVisit DateTimeNowToString())

Control State If you create a custom control that requires ViewState you can use

the ControlState property to store state information for your control ControlStateallows you to persist property information that is specific to a control and cannot be

turned off like the ViewState property To use control state in a custom control your

control must override the OnInit method and call the Register-RequiresControlStatemethod during initialization and then override the SaveControl-State and

LoadControlState methods

Hidden fields ViewState stores information in the Web page using hidden fieldsHidden fields are sent back to the server when the user submits a form however

the information is never displayed by the Web browser (unless the user chooses toview the page source) ASPNET allows you to create your own custom hidden fields

and store values that are submitted with other form data A HiddenField controlstores a single variable in its Value property and must be explicitly added to the

page You can use hidden fields only to store information for a single page so it isnot useful for storing session data If you use hidden fields you must submit your

pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which

happens if the user clicks a link) Unlike view state data hidden fields have no built-in compression encryption hashing or chunking so users can view or modify data

stored in hidden fields

Cookies Web applications can store small pieces of data in the clientrsquos Web browserby using cookies A cookie is a small amount of data that is stored either in a text file

on the client file system (if the cookie is persistent) or in memory in the clientbrowser session (if the cookie is temporary) The most common use of cookies is to

identify a single user as he or she visits multiple Web pages

Reading and Writing Cookies

A Web application creates a cookie by sending it to the client as a header in an HTTP

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1653

response The Web browser then submits the same cookie to the server with everynew request

Create a cookie -gt add a value to the ResponseCookies HttpCookieCollectionRead a cookie -gt read values in RequestCookies

Example

Check if cookie exists and display it if it does

if (RequestCookies[lastVisit] = null) Encode the cookie in case thecookie contains client-side script Label1Text =ServerHtmlEncode(RequestCookies[lastVisit]Value)

else Label1Text = No value defined

Define the cookie for the next visit ResponseCookies[lastVisit]Value =DateTimeNowToString()ResponseCookies[lastVisit]Expires =DateTimeNowAddDays(1)

If you do not define the Expires property the browser stores it in memory and the

cookie is lost if the user closes his or her browser

To delete a cookie overwrite the cookie and set an expiration date in the past Youcanrsquot directly delete cookies because they are stored on the clientrsquos computer

Controlling the Cookie Scope By default browsers wonrsquot send a cookie to a Web sitewith a different hostname You can control a cookiersquos scope to either limit the scope

to a specific folder on the Web server or expand the scope to any server in a domainTo limit the scope of a cookie to a folder set the Path property as the following

example demonstrates

Example

ResponseCookies[lastVisit]Path = Application1

Through this the scope is limited to the ldquoApplication1rdquo folder that is the browser

submits the cookie to any page with in this folder and not to pages in other folderseven if the folder is in the same server We can expand the scope to a particular

domain using the following statementExample

ResponseCookies[ldquolastVisitrdquo]Domain = ldquoContosordquo

Storing Multiple Values in a CookieThough it depends on the browser you typically canrsquot store more than 20 cookies

per site and each cookie can be a maximum of 4 KB in length To work around the

20-cookie limit you can store multiple values in a cookie as the following codedemonstratesExample

ResponseCookies[info][visit]Value = DateTimeNowToString()

ResponseCookies[info][firstName]Value = Tony

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 453

Application Pool with multiple worker process is called ldquoWeb Gardenrdquo

Now I have covered all the basic stuff like Web server Application Pool Workerprocess Now letrsquos have look how IIS process the request when a new request comes

up from client

If we look into the IIS 60 Architecture we can divided them into Two Layer

1 Kernel Mode2 User Mode

Now Kernel mode is introduced with IIS 60 which contains the HTTPSYS Sowhenever a request comes from Client to Server it will hit HTTPSYS First

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 553

Now HTTPSYS is Responsible for pass the request to particular Application poolNow here is one question How HTTPSYS comes to know where to send the

request This is not a random pickup Whenever we creates a new Application Poolthe ID of the Application Pool is being generated and itrsquos registered with the

HTTPSYS So whenever HTTPSYS Received the request from any web application itchecks for the Application Pool and based on the application pool it send the request

So this was the first steps of IIS Request Processing

Till now Client Requested for some information and request came to the Kernel levelof IIS means at HTTPSYS HTTPSYS has been identified the name of the application

pool where to send Now letrsquos see how this request moves from HTTPSYS to

Application Pool

In User Level of IIS we have Web Admin Services (WAS) which takes the requestfrom HTTPSYS and pass it to the respective application pool

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 653

When Application pool receive the request it simply pass the request to workerprocess (w3wpexe) The worker process ldquow3wpexerdquo looks up the URL of therequest in order to load the correct ISAPI extension ISAPI extensions are the IIS

way to handle requests for different resources Once ASPNET is installed it installsits own ISAPI extension (aspnet_isapidll) and adds the mapping into IIS

Note Sometimes if we install IIS after installing aspnet we need to register the

extension with IIS using aspnet_regiis command

When Worker process loads the aspnet_isapidll it start an HTTPRuntime which isthe entry point of an application HTTPRuntime is a class which calls the

ProcessRequest method to start Processing

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 753

When this methods called a new instance of HTTPContext is been created Which

is accessible using HTTPContextCurrent

+ Properties This object still remains alive during life time of object request Using

HttpContextCurrent we can access some other objects like Request ResponseSession etc

After that HttpRuntime load an HttpApplication object with the help of HttpApplicationFactory class Each and every request should pass through the

corresponding HTTPModule to reach to HTTPHandler this list of module areconfigured by the HTTPApplication

Now the concept comes called ldquoHTTPPipelinerdquo It is called a pipeline because it

contains a set of HttpModules ( For Both Webconfig and Machineconfig level) thatintercept the request on its way to the HttpHandler HTTPModules are classes that

have access to the incoming request We can also create our own HTTPModule if we

need to handle anything during upcoming request and response

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 853

HTTP Handlers are the endpoints in the HTTP pipeline All request that are passing

through the HTTPModule should reached to HTTPHandler Then HTTP Handlergenerates the output for the requested resource So when we requesting for any

aspx web pages it returns the corresponding HTML output

All the request now passes from httpModule to respective HTTPHandler then

method and the ASPNET Page life cycle starts This ends the IIS Request processingand start the ASPNET Page Lifecycle

Conclusion

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 953

When client request for some information from a web server request first reaches toHTTPSYS of IIS HTTPSYS then send the request to respective Application Pool

Application Pool then forward the request to worker process to load the ISAPIExtension which will create an HTTPRuntime Object to Process the request via

HTTPModule and HTTPHanlder After that the ASPNET Page LifeCycle events starts

One of the very common question in any dot net interview is aboult explaining ASPNET page lifecycle

ASPNET page life cycle is not very tough to know but in many books I have seen it is written insuch a manner that it seems to be very complicated

In this article I will try to explain the page life cycle as simple as possible

How it all begins

A user sits at her browser and types in a URL A web page appears with text imagesbuttonsand so forth She fills in a text box and clicks a button New data appears in response How doesthis work

When an ASPNET page is requested from the server the server loads the page into server memory processes the page sends the page to the user and then unloads it from memoryFrom the beginning of the life cycle to the end the goal is to render appropriate HTML to therequesting browser At each step methods and events are available that allow you to override thedefault behavior or add your own programmatic enhancements

There are two slightly different sequences in the life cycle one for the first time a page is loadedand a second when the page reloads itself in a postback

During the first page load the life cycle consists of the following steps

1 A request for the page is made from a browser to the web server The ASPNET Frameworkfirst determines whether the page already exists in a cache (a section of memory specificallyreserved for recently used items) If so the page is retrieved and returned to the browser and weare done If not then the actual page life cycle starts at this point

2 During the Start phase the postback mode is determined If the page was requested by adifferent page then it was not a postback If the page was returned to the server for processingand redisplay then it is a postbackThe IsPostBack and PreviousPage properties are set accordingly The Request andResponse properties of the page along with a number of other properties are alsoset

3 The Page Initialization phase contains two events often handled by your codePreInit and InitIf you do not handle these explicitly yourself ASPNET will perform the default behavior on your behalf

During the PreInit event the target device is determined before the page is initialized the master page is set the control tree is built and the controls are assigned unique IDs which are madeavailable to your code Personalization and themes are loaded and applied to the page in thisstep

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1053

PreInit is the first event in the life cycle that can be trapped and handled That is this is the firstevent that you can write your own code for to change the default behavior of initializing the page

4 During the Init event control properties are read or initialized If this is a postback it isimportant to realize that the controls wonrsquot reflect any changes to the page made before thepostbackthat happens in the PreRender phase They will contain values specified in themarkup file

5 During the Load event all the control properties are set View state information is availableand controls in the pagersquos control hierarchy can be accessed The load phase is routinelymodified in a Page_Load method

6 During the Validation phase the Validate method is called on all the validation controls on thepage The IsValid property is set for all those controls and for the page as a whole

7 During the Rendering phase personalization control and view state is saved Each control onthe page is called in succession to render itself to the browser that is to compose itself intoHTML that is included in the pagersquos Response property

It is very common to handle the PreRender event with a Page_PreRender method typicallywhen you must take some action based on the final value of some other control on the pageDuring the Render event the HTML is actuallygenerated and sent to the requesting pagealthough this event is rarely handled unless you are developing custom controls

8 Unload is the last event of the life cycle It gives you an opportunity to do any final cleanup(ie closing open files and releasing references to expensive resources such as databaseconnections)

During postback the life cycle is the same as during the first load except for the following

1 During the Load phase after initialization is complete the view state and the control state areloaded and applied as necessary

2 After the Validation phase completes postback data is processed Control event handlers arenow executed

This is important control event handlers such as a Button Click are not called until after thePage Initialization and Load events are handled

The following are the various stages a page goes through

Page Request

The request page is either parsed or compiled or fetched from the cache

Start

Page properties like the Request and Response are set The type of request is determined

specifically whether it is a new Request or it is a PostBack Culturing properties are also

determined via the pages ICulture property

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1153

Page Initialization

All the controls on the given page are initialized with a UniqueID (please donrsquot confused

this with the ID property as the UnqiueID is a unique hierarchicial identifier whichincludes the server

controlrsquos naming container) Theming is also applied at this stage

Load

If the current request is a PostBack the data from the viewstate and control state is

loaded to the appropriate properties of the controls

Validation

The Validate method of all the validator controls are fired which in turn sets the Boolean

property IsValid of the controls

Postback Event Handling

If the current request is a PostBack all event handlers are called

Rendering

ViewState data is saved for all the controls that have enabled viewstate The Render

method for all the controls is fired which writes its output to the OutputStream via a text

writer

Unload

Once the page has been rendered and sent the Pagersquos properties are unloaded (cleanup

time)

So know you have a better understanding of the various stages of a ASPNET pages lifecycle you should be aware that within each of the above stages there are events that you

can hook into so that your code is fired at the exact time that you want it to

Event Wire-up is another important concept to understand So Event wire-up is where

ASPNET looks for methods that match a naming convention (eg Page_Load Page_Initetc) and these methods are automatically fired at the appropriate event There is a page

level attribute AutoEventWireup that can be set to either true or false to enable this

behaviour

Below are some of the more popular events that you should understand as you will mostlikely be interested in them

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1253

PreInit

You can use this event to

Create recreate dynamic controls

Set a master page or theme dynamically

Access profile properties

Init

Used to read or initialize your control properties

InitComplete

Used when you need to access your properties after they have been initialized

PreLoad

Used when you need to process things before the Load event has been fired

Load

The Pagersquos OnLoad method and all of its child controlrsquos OnLoad method are firedrecursively This event is used to set properties and make database connections

Control Events

Control specific events are handled at this stage eg Click eventrsquos for the button control

LoadComplete

This stage is for when you need to access controls that have been properly loaded

PreRender

Can be used to make any lsquolast chancersquo changes to the controls before they are rendered

SaveStateComplete

This event is used for things that require view state to be saved yet not making anychanges to the controls themselves

Render

The page object calls this method on all of the controls so all the controls are written andsent to the browser

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1353

Unload

All the controls UnLoad method are fired followed by the pages UnLoad event (bottom-

up) This stage is used for closing database connections closing open files etc

It is import to understand that each server control has its very own life cycle but they arefired recursively so things may not occur at the time you think they do (they occur in

reverse order) What this means is that some events fire from the bottom up like the Init

event while others load from the top-down like the Load event

Purpose

State management is the process by which you maintain state and page information

over multiple requests for the same or different pages

Types of State Management

There are 2 types State Management

1 Client ndash Side State Management This stores information on the clients computer by embedding the information into a

Web page a uniform resource locator(url) or a cookie The techniques available tostore the state information at the client end are listed down below

a View State ndash AspNet uses View State to track the values in the Controls You can

add custom values to the view state It is used by the Aspnet page framework toautomatically save the values of the page and of each control just prior to rendering

to the page When the page is posted one of the first tasks performed by page

processing is to restore view state

b Control State ndash If you create a custom control that requires view state to work

properly you should use control state to ensure other developers donrsquot break yourcontrol by disabling view state

c Hidden fields ndash Like view state hidden fields store data in an HTML form without

displaying it in the users browser The data is available only when the form isprocessed

d Cookies ndash Cookies store a value in the users browser that the browser sends with

every page request to the same server Cookies are the best way to store state datathat must be available for multiple Web pages on a web site

e Query Strings - Query strings store values in the URL that are visible to the userUse query strings when you want a user to be able to e-mail or instant message

state data with a URL

2 Server ndash Side State Management

a Application State - Application State information is available to all pagesregardless of which user requests a page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1453

b Session State ndash Session State information is available to all pages opened by auser during a single visit

Both application state and session state information is lost when the application

restarts To persist user data between application restarts you can store it usingprofile properties

Implementation Procedure

Client ndash Side State Management

View State

The ViewState property provides a dictionary object for retaining values betweenmultiple requests for the same page When an ASPNET page is processed the

current state of the page and controls is hashed into a string and saved in the pageas a hidden field If the data is too long for a single field then ASPNET performs

view state chunking (new in ASPNET 20) to split it across multiple hidden fields

The following code sample demonstrates how view state adds data as a hidden formwithin a Web pagersquos HTML

ltinput type=hidden name=__VIEWSTATE id=__VIEWSTATErdquovalue=wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHnrt75XFpMGnqjqHlH66cdw== gt

Encrypting of the View State You can enable view state encryption to make it more

difficult for attackers and malicious users to directly read view state informationThough this adds processing overhead to the Web server it supports in storing

confidential information in view state To configure view state encryption for an

application does the following

ltConfigurationgt

ltsystemwebgt

ltpages viewStateEncryptionMode=Alwaysgt

ltsystemwebgt

ltconfigurationgt

Alternatively you can enable view state encryption for a specific page by setting thevalue in the page directive as the following sample demonstrates

lt Page Language=C AutoEventWireup=true CodeFile=DefaultaspxcsInherits=_Default ViewStateEncryptionMode=Alwaysgt

View State is enabled by default but if you can disable it by setting the

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1553

EnableViewState property for each web control to false This reduces the serverprocessing time and decreases page size

Reading and Writing Custom View State DataIf you have a value that yoursquod like to keep track of while the user is visiting a single

ASPNET Web page adding a custom value to ViewState is the most efficient andsecure way to do that However ViewState is lost if the user visits a different Web

page so it is useful only for temporarily storing valuesExample Determine the time of last visit to the page

Check if View State object exists and display it if it does

If (ViewState [lastVisit]= null)

Label1Text = (string)ViewState[lastVisit] else

Label1Text = lastVisit ViewState not defined

Define the ViewState object for the next page viewViewStateAdd(lastVisit DateTimeNowToString())

Control State If you create a custom control that requires ViewState you can use

the ControlState property to store state information for your control ControlStateallows you to persist property information that is specific to a control and cannot be

turned off like the ViewState property To use control state in a custom control your

control must override the OnInit method and call the Register-RequiresControlStatemethod during initialization and then override the SaveControl-State and

LoadControlState methods

Hidden fields ViewState stores information in the Web page using hidden fieldsHidden fields are sent back to the server when the user submits a form however

the information is never displayed by the Web browser (unless the user chooses toview the page source) ASPNET allows you to create your own custom hidden fields

and store values that are submitted with other form data A HiddenField controlstores a single variable in its Value property and must be explicitly added to the

page You can use hidden fields only to store information for a single page so it isnot useful for storing session data If you use hidden fields you must submit your

pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which

happens if the user clicks a link) Unlike view state data hidden fields have no built-in compression encryption hashing or chunking so users can view or modify data

stored in hidden fields

Cookies Web applications can store small pieces of data in the clientrsquos Web browserby using cookies A cookie is a small amount of data that is stored either in a text file

on the client file system (if the cookie is persistent) or in memory in the clientbrowser session (if the cookie is temporary) The most common use of cookies is to

identify a single user as he or she visits multiple Web pages

Reading and Writing Cookies

A Web application creates a cookie by sending it to the client as a header in an HTTP

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1653

response The Web browser then submits the same cookie to the server with everynew request

Create a cookie -gt add a value to the ResponseCookies HttpCookieCollectionRead a cookie -gt read values in RequestCookies

Example

Check if cookie exists and display it if it does

if (RequestCookies[lastVisit] = null) Encode the cookie in case thecookie contains client-side script Label1Text =ServerHtmlEncode(RequestCookies[lastVisit]Value)

else Label1Text = No value defined

Define the cookie for the next visit ResponseCookies[lastVisit]Value =DateTimeNowToString()ResponseCookies[lastVisit]Expires =DateTimeNowAddDays(1)

If you do not define the Expires property the browser stores it in memory and the

cookie is lost if the user closes his or her browser

To delete a cookie overwrite the cookie and set an expiration date in the past Youcanrsquot directly delete cookies because they are stored on the clientrsquos computer

Controlling the Cookie Scope By default browsers wonrsquot send a cookie to a Web sitewith a different hostname You can control a cookiersquos scope to either limit the scope

to a specific folder on the Web server or expand the scope to any server in a domainTo limit the scope of a cookie to a folder set the Path property as the following

example demonstrates

Example

ResponseCookies[lastVisit]Path = Application1

Through this the scope is limited to the ldquoApplication1rdquo folder that is the browser

submits the cookie to any page with in this folder and not to pages in other folderseven if the folder is in the same server We can expand the scope to a particular

domain using the following statementExample

ResponseCookies[ldquolastVisitrdquo]Domain = ldquoContosordquo

Storing Multiple Values in a CookieThough it depends on the browser you typically canrsquot store more than 20 cookies

per site and each cookie can be a maximum of 4 KB in length To work around the

20-cookie limit you can store multiple values in a cookie as the following codedemonstratesExample

ResponseCookies[info][visit]Value = DateTimeNowToString()

ResponseCookies[info][firstName]Value = Tony

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 553

Now HTTPSYS is Responsible for pass the request to particular Application poolNow here is one question How HTTPSYS comes to know where to send the

request This is not a random pickup Whenever we creates a new Application Poolthe ID of the Application Pool is being generated and itrsquos registered with the

HTTPSYS So whenever HTTPSYS Received the request from any web application itchecks for the Application Pool and based on the application pool it send the request

So this was the first steps of IIS Request Processing

Till now Client Requested for some information and request came to the Kernel levelof IIS means at HTTPSYS HTTPSYS has been identified the name of the application

pool where to send Now letrsquos see how this request moves from HTTPSYS to

Application Pool

In User Level of IIS we have Web Admin Services (WAS) which takes the requestfrom HTTPSYS and pass it to the respective application pool

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 653

When Application pool receive the request it simply pass the request to workerprocess (w3wpexe) The worker process ldquow3wpexerdquo looks up the URL of therequest in order to load the correct ISAPI extension ISAPI extensions are the IIS

way to handle requests for different resources Once ASPNET is installed it installsits own ISAPI extension (aspnet_isapidll) and adds the mapping into IIS

Note Sometimes if we install IIS after installing aspnet we need to register the

extension with IIS using aspnet_regiis command

When Worker process loads the aspnet_isapidll it start an HTTPRuntime which isthe entry point of an application HTTPRuntime is a class which calls the

ProcessRequest method to start Processing

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 753

When this methods called a new instance of HTTPContext is been created Which

is accessible using HTTPContextCurrent

+ Properties This object still remains alive during life time of object request Using

HttpContextCurrent we can access some other objects like Request ResponseSession etc

After that HttpRuntime load an HttpApplication object with the help of HttpApplicationFactory class Each and every request should pass through the

corresponding HTTPModule to reach to HTTPHandler this list of module areconfigured by the HTTPApplication

Now the concept comes called ldquoHTTPPipelinerdquo It is called a pipeline because it

contains a set of HttpModules ( For Both Webconfig and Machineconfig level) thatintercept the request on its way to the HttpHandler HTTPModules are classes that

have access to the incoming request We can also create our own HTTPModule if we

need to handle anything during upcoming request and response

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 853

HTTP Handlers are the endpoints in the HTTP pipeline All request that are passing

through the HTTPModule should reached to HTTPHandler Then HTTP Handlergenerates the output for the requested resource So when we requesting for any

aspx web pages it returns the corresponding HTML output

All the request now passes from httpModule to respective HTTPHandler then

method and the ASPNET Page life cycle starts This ends the IIS Request processingand start the ASPNET Page Lifecycle

Conclusion

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 953

When client request for some information from a web server request first reaches toHTTPSYS of IIS HTTPSYS then send the request to respective Application Pool

Application Pool then forward the request to worker process to load the ISAPIExtension which will create an HTTPRuntime Object to Process the request via

HTTPModule and HTTPHanlder After that the ASPNET Page LifeCycle events starts

One of the very common question in any dot net interview is aboult explaining ASPNET page lifecycle

ASPNET page life cycle is not very tough to know but in many books I have seen it is written insuch a manner that it seems to be very complicated

In this article I will try to explain the page life cycle as simple as possible

How it all begins

A user sits at her browser and types in a URL A web page appears with text imagesbuttonsand so forth She fills in a text box and clicks a button New data appears in response How doesthis work

When an ASPNET page is requested from the server the server loads the page into server memory processes the page sends the page to the user and then unloads it from memoryFrom the beginning of the life cycle to the end the goal is to render appropriate HTML to therequesting browser At each step methods and events are available that allow you to override thedefault behavior or add your own programmatic enhancements

There are two slightly different sequences in the life cycle one for the first time a page is loadedand a second when the page reloads itself in a postback

During the first page load the life cycle consists of the following steps

1 A request for the page is made from a browser to the web server The ASPNET Frameworkfirst determines whether the page already exists in a cache (a section of memory specificallyreserved for recently used items) If so the page is retrieved and returned to the browser and weare done If not then the actual page life cycle starts at this point

2 During the Start phase the postback mode is determined If the page was requested by adifferent page then it was not a postback If the page was returned to the server for processingand redisplay then it is a postbackThe IsPostBack and PreviousPage properties are set accordingly The Request andResponse properties of the page along with a number of other properties are alsoset

3 The Page Initialization phase contains two events often handled by your codePreInit and InitIf you do not handle these explicitly yourself ASPNET will perform the default behavior on your behalf

During the PreInit event the target device is determined before the page is initialized the master page is set the control tree is built and the controls are assigned unique IDs which are madeavailable to your code Personalization and themes are loaded and applied to the page in thisstep

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1053

PreInit is the first event in the life cycle that can be trapped and handled That is this is the firstevent that you can write your own code for to change the default behavior of initializing the page

4 During the Init event control properties are read or initialized If this is a postback it isimportant to realize that the controls wonrsquot reflect any changes to the page made before thepostbackthat happens in the PreRender phase They will contain values specified in themarkup file

5 During the Load event all the control properties are set View state information is availableand controls in the pagersquos control hierarchy can be accessed The load phase is routinelymodified in a Page_Load method

6 During the Validation phase the Validate method is called on all the validation controls on thepage The IsValid property is set for all those controls and for the page as a whole

7 During the Rendering phase personalization control and view state is saved Each control onthe page is called in succession to render itself to the browser that is to compose itself intoHTML that is included in the pagersquos Response property

It is very common to handle the PreRender event with a Page_PreRender method typicallywhen you must take some action based on the final value of some other control on the pageDuring the Render event the HTML is actuallygenerated and sent to the requesting pagealthough this event is rarely handled unless you are developing custom controls

8 Unload is the last event of the life cycle It gives you an opportunity to do any final cleanup(ie closing open files and releasing references to expensive resources such as databaseconnections)

During postback the life cycle is the same as during the first load except for the following

1 During the Load phase after initialization is complete the view state and the control state areloaded and applied as necessary

2 After the Validation phase completes postback data is processed Control event handlers arenow executed

This is important control event handlers such as a Button Click are not called until after thePage Initialization and Load events are handled

The following are the various stages a page goes through

Page Request

The request page is either parsed or compiled or fetched from the cache

Start

Page properties like the Request and Response are set The type of request is determined

specifically whether it is a new Request or it is a PostBack Culturing properties are also

determined via the pages ICulture property

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1153

Page Initialization

All the controls on the given page are initialized with a UniqueID (please donrsquot confused

this with the ID property as the UnqiueID is a unique hierarchicial identifier whichincludes the server

controlrsquos naming container) Theming is also applied at this stage

Load

If the current request is a PostBack the data from the viewstate and control state is

loaded to the appropriate properties of the controls

Validation

The Validate method of all the validator controls are fired which in turn sets the Boolean

property IsValid of the controls

Postback Event Handling

If the current request is a PostBack all event handlers are called

Rendering

ViewState data is saved for all the controls that have enabled viewstate The Render

method for all the controls is fired which writes its output to the OutputStream via a text

writer

Unload

Once the page has been rendered and sent the Pagersquos properties are unloaded (cleanup

time)

So know you have a better understanding of the various stages of a ASPNET pages lifecycle you should be aware that within each of the above stages there are events that you

can hook into so that your code is fired at the exact time that you want it to

Event Wire-up is another important concept to understand So Event wire-up is where

ASPNET looks for methods that match a naming convention (eg Page_Load Page_Initetc) and these methods are automatically fired at the appropriate event There is a page

level attribute AutoEventWireup that can be set to either true or false to enable this

behaviour

Below are some of the more popular events that you should understand as you will mostlikely be interested in them

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1253

PreInit

You can use this event to

Create recreate dynamic controls

Set a master page or theme dynamically

Access profile properties

Init

Used to read or initialize your control properties

InitComplete

Used when you need to access your properties after they have been initialized

PreLoad

Used when you need to process things before the Load event has been fired

Load

The Pagersquos OnLoad method and all of its child controlrsquos OnLoad method are firedrecursively This event is used to set properties and make database connections

Control Events

Control specific events are handled at this stage eg Click eventrsquos for the button control

LoadComplete

This stage is for when you need to access controls that have been properly loaded

PreRender

Can be used to make any lsquolast chancersquo changes to the controls before they are rendered

SaveStateComplete

This event is used for things that require view state to be saved yet not making anychanges to the controls themselves

Render

The page object calls this method on all of the controls so all the controls are written andsent to the browser

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1353

Unload

All the controls UnLoad method are fired followed by the pages UnLoad event (bottom-

up) This stage is used for closing database connections closing open files etc

It is import to understand that each server control has its very own life cycle but they arefired recursively so things may not occur at the time you think they do (they occur in

reverse order) What this means is that some events fire from the bottom up like the Init

event while others load from the top-down like the Load event

Purpose

State management is the process by which you maintain state and page information

over multiple requests for the same or different pages

Types of State Management

There are 2 types State Management

1 Client ndash Side State Management This stores information on the clients computer by embedding the information into a

Web page a uniform resource locator(url) or a cookie The techniques available tostore the state information at the client end are listed down below

a View State ndash AspNet uses View State to track the values in the Controls You can

add custom values to the view state It is used by the Aspnet page framework toautomatically save the values of the page and of each control just prior to rendering

to the page When the page is posted one of the first tasks performed by page

processing is to restore view state

b Control State ndash If you create a custom control that requires view state to work

properly you should use control state to ensure other developers donrsquot break yourcontrol by disabling view state

c Hidden fields ndash Like view state hidden fields store data in an HTML form without

displaying it in the users browser The data is available only when the form isprocessed

d Cookies ndash Cookies store a value in the users browser that the browser sends with

every page request to the same server Cookies are the best way to store state datathat must be available for multiple Web pages on a web site

e Query Strings - Query strings store values in the URL that are visible to the userUse query strings when you want a user to be able to e-mail or instant message

state data with a URL

2 Server ndash Side State Management

a Application State - Application State information is available to all pagesregardless of which user requests a page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1453

b Session State ndash Session State information is available to all pages opened by auser during a single visit

Both application state and session state information is lost when the application

restarts To persist user data between application restarts you can store it usingprofile properties

Implementation Procedure

Client ndash Side State Management

View State

The ViewState property provides a dictionary object for retaining values betweenmultiple requests for the same page When an ASPNET page is processed the

current state of the page and controls is hashed into a string and saved in the pageas a hidden field If the data is too long for a single field then ASPNET performs

view state chunking (new in ASPNET 20) to split it across multiple hidden fields

The following code sample demonstrates how view state adds data as a hidden formwithin a Web pagersquos HTML

ltinput type=hidden name=__VIEWSTATE id=__VIEWSTATErdquovalue=wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHnrt75XFpMGnqjqHlH66cdw== gt

Encrypting of the View State You can enable view state encryption to make it more

difficult for attackers and malicious users to directly read view state informationThough this adds processing overhead to the Web server it supports in storing

confidential information in view state To configure view state encryption for an

application does the following

ltConfigurationgt

ltsystemwebgt

ltpages viewStateEncryptionMode=Alwaysgt

ltsystemwebgt

ltconfigurationgt

Alternatively you can enable view state encryption for a specific page by setting thevalue in the page directive as the following sample demonstrates

lt Page Language=C AutoEventWireup=true CodeFile=DefaultaspxcsInherits=_Default ViewStateEncryptionMode=Alwaysgt

View State is enabled by default but if you can disable it by setting the

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1553

EnableViewState property for each web control to false This reduces the serverprocessing time and decreases page size

Reading and Writing Custom View State DataIf you have a value that yoursquod like to keep track of while the user is visiting a single

ASPNET Web page adding a custom value to ViewState is the most efficient andsecure way to do that However ViewState is lost if the user visits a different Web

page so it is useful only for temporarily storing valuesExample Determine the time of last visit to the page

Check if View State object exists and display it if it does

If (ViewState [lastVisit]= null)

Label1Text = (string)ViewState[lastVisit] else

Label1Text = lastVisit ViewState not defined

Define the ViewState object for the next page viewViewStateAdd(lastVisit DateTimeNowToString())

Control State If you create a custom control that requires ViewState you can use

the ControlState property to store state information for your control ControlStateallows you to persist property information that is specific to a control and cannot be

turned off like the ViewState property To use control state in a custom control your

control must override the OnInit method and call the Register-RequiresControlStatemethod during initialization and then override the SaveControl-State and

LoadControlState methods

Hidden fields ViewState stores information in the Web page using hidden fieldsHidden fields are sent back to the server when the user submits a form however

the information is never displayed by the Web browser (unless the user chooses toview the page source) ASPNET allows you to create your own custom hidden fields

and store values that are submitted with other form data A HiddenField controlstores a single variable in its Value property and must be explicitly added to the

page You can use hidden fields only to store information for a single page so it isnot useful for storing session data If you use hidden fields you must submit your

pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which

happens if the user clicks a link) Unlike view state data hidden fields have no built-in compression encryption hashing or chunking so users can view or modify data

stored in hidden fields

Cookies Web applications can store small pieces of data in the clientrsquos Web browserby using cookies A cookie is a small amount of data that is stored either in a text file

on the client file system (if the cookie is persistent) or in memory in the clientbrowser session (if the cookie is temporary) The most common use of cookies is to

identify a single user as he or she visits multiple Web pages

Reading and Writing Cookies

A Web application creates a cookie by sending it to the client as a header in an HTTP

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1653

response The Web browser then submits the same cookie to the server with everynew request

Create a cookie -gt add a value to the ResponseCookies HttpCookieCollectionRead a cookie -gt read values in RequestCookies

Example

Check if cookie exists and display it if it does

if (RequestCookies[lastVisit] = null) Encode the cookie in case thecookie contains client-side script Label1Text =ServerHtmlEncode(RequestCookies[lastVisit]Value)

else Label1Text = No value defined

Define the cookie for the next visit ResponseCookies[lastVisit]Value =DateTimeNowToString()ResponseCookies[lastVisit]Expires =DateTimeNowAddDays(1)

If you do not define the Expires property the browser stores it in memory and the

cookie is lost if the user closes his or her browser

To delete a cookie overwrite the cookie and set an expiration date in the past Youcanrsquot directly delete cookies because they are stored on the clientrsquos computer

Controlling the Cookie Scope By default browsers wonrsquot send a cookie to a Web sitewith a different hostname You can control a cookiersquos scope to either limit the scope

to a specific folder on the Web server or expand the scope to any server in a domainTo limit the scope of a cookie to a folder set the Path property as the following

example demonstrates

Example

ResponseCookies[lastVisit]Path = Application1

Through this the scope is limited to the ldquoApplication1rdquo folder that is the browser

submits the cookie to any page with in this folder and not to pages in other folderseven if the folder is in the same server We can expand the scope to a particular

domain using the following statementExample

ResponseCookies[ldquolastVisitrdquo]Domain = ldquoContosordquo

Storing Multiple Values in a CookieThough it depends on the browser you typically canrsquot store more than 20 cookies

per site and each cookie can be a maximum of 4 KB in length To work around the

20-cookie limit you can store multiple values in a cookie as the following codedemonstratesExample

ResponseCookies[info][visit]Value = DateTimeNowToString()

ResponseCookies[info][firstName]Value = Tony

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 653

When Application pool receive the request it simply pass the request to workerprocess (w3wpexe) The worker process ldquow3wpexerdquo looks up the URL of therequest in order to load the correct ISAPI extension ISAPI extensions are the IIS

way to handle requests for different resources Once ASPNET is installed it installsits own ISAPI extension (aspnet_isapidll) and adds the mapping into IIS

Note Sometimes if we install IIS after installing aspnet we need to register the

extension with IIS using aspnet_regiis command

When Worker process loads the aspnet_isapidll it start an HTTPRuntime which isthe entry point of an application HTTPRuntime is a class which calls the

ProcessRequest method to start Processing

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 753

When this methods called a new instance of HTTPContext is been created Which

is accessible using HTTPContextCurrent

+ Properties This object still remains alive during life time of object request Using

HttpContextCurrent we can access some other objects like Request ResponseSession etc

After that HttpRuntime load an HttpApplication object with the help of HttpApplicationFactory class Each and every request should pass through the

corresponding HTTPModule to reach to HTTPHandler this list of module areconfigured by the HTTPApplication

Now the concept comes called ldquoHTTPPipelinerdquo It is called a pipeline because it

contains a set of HttpModules ( For Both Webconfig and Machineconfig level) thatintercept the request on its way to the HttpHandler HTTPModules are classes that

have access to the incoming request We can also create our own HTTPModule if we

need to handle anything during upcoming request and response

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 853

HTTP Handlers are the endpoints in the HTTP pipeline All request that are passing

through the HTTPModule should reached to HTTPHandler Then HTTP Handlergenerates the output for the requested resource So when we requesting for any

aspx web pages it returns the corresponding HTML output

All the request now passes from httpModule to respective HTTPHandler then

method and the ASPNET Page life cycle starts This ends the IIS Request processingand start the ASPNET Page Lifecycle

Conclusion

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 953

When client request for some information from a web server request first reaches toHTTPSYS of IIS HTTPSYS then send the request to respective Application Pool

Application Pool then forward the request to worker process to load the ISAPIExtension which will create an HTTPRuntime Object to Process the request via

HTTPModule and HTTPHanlder After that the ASPNET Page LifeCycle events starts

One of the very common question in any dot net interview is aboult explaining ASPNET page lifecycle

ASPNET page life cycle is not very tough to know but in many books I have seen it is written insuch a manner that it seems to be very complicated

In this article I will try to explain the page life cycle as simple as possible

How it all begins

A user sits at her browser and types in a URL A web page appears with text imagesbuttonsand so forth She fills in a text box and clicks a button New data appears in response How doesthis work

When an ASPNET page is requested from the server the server loads the page into server memory processes the page sends the page to the user and then unloads it from memoryFrom the beginning of the life cycle to the end the goal is to render appropriate HTML to therequesting browser At each step methods and events are available that allow you to override thedefault behavior or add your own programmatic enhancements

There are two slightly different sequences in the life cycle one for the first time a page is loadedand a second when the page reloads itself in a postback

During the first page load the life cycle consists of the following steps

1 A request for the page is made from a browser to the web server The ASPNET Frameworkfirst determines whether the page already exists in a cache (a section of memory specificallyreserved for recently used items) If so the page is retrieved and returned to the browser and weare done If not then the actual page life cycle starts at this point

2 During the Start phase the postback mode is determined If the page was requested by adifferent page then it was not a postback If the page was returned to the server for processingand redisplay then it is a postbackThe IsPostBack and PreviousPage properties are set accordingly The Request andResponse properties of the page along with a number of other properties are alsoset

3 The Page Initialization phase contains two events often handled by your codePreInit and InitIf you do not handle these explicitly yourself ASPNET will perform the default behavior on your behalf

During the PreInit event the target device is determined before the page is initialized the master page is set the control tree is built and the controls are assigned unique IDs which are madeavailable to your code Personalization and themes are loaded and applied to the page in thisstep

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1053

PreInit is the first event in the life cycle that can be trapped and handled That is this is the firstevent that you can write your own code for to change the default behavior of initializing the page

4 During the Init event control properties are read or initialized If this is a postback it isimportant to realize that the controls wonrsquot reflect any changes to the page made before thepostbackthat happens in the PreRender phase They will contain values specified in themarkup file

5 During the Load event all the control properties are set View state information is availableand controls in the pagersquos control hierarchy can be accessed The load phase is routinelymodified in a Page_Load method

6 During the Validation phase the Validate method is called on all the validation controls on thepage The IsValid property is set for all those controls and for the page as a whole

7 During the Rendering phase personalization control and view state is saved Each control onthe page is called in succession to render itself to the browser that is to compose itself intoHTML that is included in the pagersquos Response property

It is very common to handle the PreRender event with a Page_PreRender method typicallywhen you must take some action based on the final value of some other control on the pageDuring the Render event the HTML is actuallygenerated and sent to the requesting pagealthough this event is rarely handled unless you are developing custom controls

8 Unload is the last event of the life cycle It gives you an opportunity to do any final cleanup(ie closing open files and releasing references to expensive resources such as databaseconnections)

During postback the life cycle is the same as during the first load except for the following

1 During the Load phase after initialization is complete the view state and the control state areloaded and applied as necessary

2 After the Validation phase completes postback data is processed Control event handlers arenow executed

This is important control event handlers such as a Button Click are not called until after thePage Initialization and Load events are handled

The following are the various stages a page goes through

Page Request

The request page is either parsed or compiled or fetched from the cache

Start

Page properties like the Request and Response are set The type of request is determined

specifically whether it is a new Request or it is a PostBack Culturing properties are also

determined via the pages ICulture property

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1153

Page Initialization

All the controls on the given page are initialized with a UniqueID (please donrsquot confused

this with the ID property as the UnqiueID is a unique hierarchicial identifier whichincludes the server

controlrsquos naming container) Theming is also applied at this stage

Load

If the current request is a PostBack the data from the viewstate and control state is

loaded to the appropriate properties of the controls

Validation

The Validate method of all the validator controls are fired which in turn sets the Boolean

property IsValid of the controls

Postback Event Handling

If the current request is a PostBack all event handlers are called

Rendering

ViewState data is saved for all the controls that have enabled viewstate The Render

method for all the controls is fired which writes its output to the OutputStream via a text

writer

Unload

Once the page has been rendered and sent the Pagersquos properties are unloaded (cleanup

time)

So know you have a better understanding of the various stages of a ASPNET pages lifecycle you should be aware that within each of the above stages there are events that you

can hook into so that your code is fired at the exact time that you want it to

Event Wire-up is another important concept to understand So Event wire-up is where

ASPNET looks for methods that match a naming convention (eg Page_Load Page_Initetc) and these methods are automatically fired at the appropriate event There is a page

level attribute AutoEventWireup that can be set to either true or false to enable this

behaviour

Below are some of the more popular events that you should understand as you will mostlikely be interested in them

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1253

PreInit

You can use this event to

Create recreate dynamic controls

Set a master page or theme dynamically

Access profile properties

Init

Used to read or initialize your control properties

InitComplete

Used when you need to access your properties after they have been initialized

PreLoad

Used when you need to process things before the Load event has been fired

Load

The Pagersquos OnLoad method and all of its child controlrsquos OnLoad method are firedrecursively This event is used to set properties and make database connections

Control Events

Control specific events are handled at this stage eg Click eventrsquos for the button control

LoadComplete

This stage is for when you need to access controls that have been properly loaded

PreRender

Can be used to make any lsquolast chancersquo changes to the controls before they are rendered

SaveStateComplete

This event is used for things that require view state to be saved yet not making anychanges to the controls themselves

Render

The page object calls this method on all of the controls so all the controls are written andsent to the browser

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1353

Unload

All the controls UnLoad method are fired followed by the pages UnLoad event (bottom-

up) This stage is used for closing database connections closing open files etc

It is import to understand that each server control has its very own life cycle but they arefired recursively so things may not occur at the time you think they do (they occur in

reverse order) What this means is that some events fire from the bottom up like the Init

event while others load from the top-down like the Load event

Purpose

State management is the process by which you maintain state and page information

over multiple requests for the same or different pages

Types of State Management

There are 2 types State Management

1 Client ndash Side State Management This stores information on the clients computer by embedding the information into a

Web page a uniform resource locator(url) or a cookie The techniques available tostore the state information at the client end are listed down below

a View State ndash AspNet uses View State to track the values in the Controls You can

add custom values to the view state It is used by the Aspnet page framework toautomatically save the values of the page and of each control just prior to rendering

to the page When the page is posted one of the first tasks performed by page

processing is to restore view state

b Control State ndash If you create a custom control that requires view state to work

properly you should use control state to ensure other developers donrsquot break yourcontrol by disabling view state

c Hidden fields ndash Like view state hidden fields store data in an HTML form without

displaying it in the users browser The data is available only when the form isprocessed

d Cookies ndash Cookies store a value in the users browser that the browser sends with

every page request to the same server Cookies are the best way to store state datathat must be available for multiple Web pages on a web site

e Query Strings - Query strings store values in the URL that are visible to the userUse query strings when you want a user to be able to e-mail or instant message

state data with a URL

2 Server ndash Side State Management

a Application State - Application State information is available to all pagesregardless of which user requests a page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1453

b Session State ndash Session State information is available to all pages opened by auser during a single visit

Both application state and session state information is lost when the application

restarts To persist user data between application restarts you can store it usingprofile properties

Implementation Procedure

Client ndash Side State Management

View State

The ViewState property provides a dictionary object for retaining values betweenmultiple requests for the same page When an ASPNET page is processed the

current state of the page and controls is hashed into a string and saved in the pageas a hidden field If the data is too long for a single field then ASPNET performs

view state chunking (new in ASPNET 20) to split it across multiple hidden fields

The following code sample demonstrates how view state adds data as a hidden formwithin a Web pagersquos HTML

ltinput type=hidden name=__VIEWSTATE id=__VIEWSTATErdquovalue=wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHnrt75XFpMGnqjqHlH66cdw== gt

Encrypting of the View State You can enable view state encryption to make it more

difficult for attackers and malicious users to directly read view state informationThough this adds processing overhead to the Web server it supports in storing

confidential information in view state To configure view state encryption for an

application does the following

ltConfigurationgt

ltsystemwebgt

ltpages viewStateEncryptionMode=Alwaysgt

ltsystemwebgt

ltconfigurationgt

Alternatively you can enable view state encryption for a specific page by setting thevalue in the page directive as the following sample demonstrates

lt Page Language=C AutoEventWireup=true CodeFile=DefaultaspxcsInherits=_Default ViewStateEncryptionMode=Alwaysgt

View State is enabled by default but if you can disable it by setting the

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1553

EnableViewState property for each web control to false This reduces the serverprocessing time and decreases page size

Reading and Writing Custom View State DataIf you have a value that yoursquod like to keep track of while the user is visiting a single

ASPNET Web page adding a custom value to ViewState is the most efficient andsecure way to do that However ViewState is lost if the user visits a different Web

page so it is useful only for temporarily storing valuesExample Determine the time of last visit to the page

Check if View State object exists and display it if it does

If (ViewState [lastVisit]= null)

Label1Text = (string)ViewState[lastVisit] else

Label1Text = lastVisit ViewState not defined

Define the ViewState object for the next page viewViewStateAdd(lastVisit DateTimeNowToString())

Control State If you create a custom control that requires ViewState you can use

the ControlState property to store state information for your control ControlStateallows you to persist property information that is specific to a control and cannot be

turned off like the ViewState property To use control state in a custom control your

control must override the OnInit method and call the Register-RequiresControlStatemethod during initialization and then override the SaveControl-State and

LoadControlState methods

Hidden fields ViewState stores information in the Web page using hidden fieldsHidden fields are sent back to the server when the user submits a form however

the information is never displayed by the Web browser (unless the user chooses toview the page source) ASPNET allows you to create your own custom hidden fields

and store values that are submitted with other form data A HiddenField controlstores a single variable in its Value property and must be explicitly added to the

page You can use hidden fields only to store information for a single page so it isnot useful for storing session data If you use hidden fields you must submit your

pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which

happens if the user clicks a link) Unlike view state data hidden fields have no built-in compression encryption hashing or chunking so users can view or modify data

stored in hidden fields

Cookies Web applications can store small pieces of data in the clientrsquos Web browserby using cookies A cookie is a small amount of data that is stored either in a text file

on the client file system (if the cookie is persistent) or in memory in the clientbrowser session (if the cookie is temporary) The most common use of cookies is to

identify a single user as he or she visits multiple Web pages

Reading and Writing Cookies

A Web application creates a cookie by sending it to the client as a header in an HTTP

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1653

response The Web browser then submits the same cookie to the server with everynew request

Create a cookie -gt add a value to the ResponseCookies HttpCookieCollectionRead a cookie -gt read values in RequestCookies

Example

Check if cookie exists and display it if it does

if (RequestCookies[lastVisit] = null) Encode the cookie in case thecookie contains client-side script Label1Text =ServerHtmlEncode(RequestCookies[lastVisit]Value)

else Label1Text = No value defined

Define the cookie for the next visit ResponseCookies[lastVisit]Value =DateTimeNowToString()ResponseCookies[lastVisit]Expires =DateTimeNowAddDays(1)

If you do not define the Expires property the browser stores it in memory and the

cookie is lost if the user closes his or her browser

To delete a cookie overwrite the cookie and set an expiration date in the past Youcanrsquot directly delete cookies because they are stored on the clientrsquos computer

Controlling the Cookie Scope By default browsers wonrsquot send a cookie to a Web sitewith a different hostname You can control a cookiersquos scope to either limit the scope

to a specific folder on the Web server or expand the scope to any server in a domainTo limit the scope of a cookie to a folder set the Path property as the following

example demonstrates

Example

ResponseCookies[lastVisit]Path = Application1

Through this the scope is limited to the ldquoApplication1rdquo folder that is the browser

submits the cookie to any page with in this folder and not to pages in other folderseven if the folder is in the same server We can expand the scope to a particular

domain using the following statementExample

ResponseCookies[ldquolastVisitrdquo]Domain = ldquoContosordquo

Storing Multiple Values in a CookieThough it depends on the browser you typically canrsquot store more than 20 cookies

per site and each cookie can be a maximum of 4 KB in length To work around the

20-cookie limit you can store multiple values in a cookie as the following codedemonstratesExample

ResponseCookies[info][visit]Value = DateTimeNowToString()

ResponseCookies[info][firstName]Value = Tony

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 753

When this methods called a new instance of HTTPContext is been created Which

is accessible using HTTPContextCurrent

+ Properties This object still remains alive during life time of object request Using

HttpContextCurrent we can access some other objects like Request ResponseSession etc

After that HttpRuntime load an HttpApplication object with the help of HttpApplicationFactory class Each and every request should pass through the

corresponding HTTPModule to reach to HTTPHandler this list of module areconfigured by the HTTPApplication

Now the concept comes called ldquoHTTPPipelinerdquo It is called a pipeline because it

contains a set of HttpModules ( For Both Webconfig and Machineconfig level) thatintercept the request on its way to the HttpHandler HTTPModules are classes that

have access to the incoming request We can also create our own HTTPModule if we

need to handle anything during upcoming request and response

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 853

HTTP Handlers are the endpoints in the HTTP pipeline All request that are passing

through the HTTPModule should reached to HTTPHandler Then HTTP Handlergenerates the output for the requested resource So when we requesting for any

aspx web pages it returns the corresponding HTML output

All the request now passes from httpModule to respective HTTPHandler then

method and the ASPNET Page life cycle starts This ends the IIS Request processingand start the ASPNET Page Lifecycle

Conclusion

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 953

When client request for some information from a web server request first reaches toHTTPSYS of IIS HTTPSYS then send the request to respective Application Pool

Application Pool then forward the request to worker process to load the ISAPIExtension which will create an HTTPRuntime Object to Process the request via

HTTPModule and HTTPHanlder After that the ASPNET Page LifeCycle events starts

One of the very common question in any dot net interview is aboult explaining ASPNET page lifecycle

ASPNET page life cycle is not very tough to know but in many books I have seen it is written insuch a manner that it seems to be very complicated

In this article I will try to explain the page life cycle as simple as possible

How it all begins

A user sits at her browser and types in a URL A web page appears with text imagesbuttonsand so forth She fills in a text box and clicks a button New data appears in response How doesthis work

When an ASPNET page is requested from the server the server loads the page into server memory processes the page sends the page to the user and then unloads it from memoryFrom the beginning of the life cycle to the end the goal is to render appropriate HTML to therequesting browser At each step methods and events are available that allow you to override thedefault behavior or add your own programmatic enhancements

There are two slightly different sequences in the life cycle one for the first time a page is loadedand a second when the page reloads itself in a postback

During the first page load the life cycle consists of the following steps

1 A request for the page is made from a browser to the web server The ASPNET Frameworkfirst determines whether the page already exists in a cache (a section of memory specificallyreserved for recently used items) If so the page is retrieved and returned to the browser and weare done If not then the actual page life cycle starts at this point

2 During the Start phase the postback mode is determined If the page was requested by adifferent page then it was not a postback If the page was returned to the server for processingand redisplay then it is a postbackThe IsPostBack and PreviousPage properties are set accordingly The Request andResponse properties of the page along with a number of other properties are alsoset

3 The Page Initialization phase contains two events often handled by your codePreInit and InitIf you do not handle these explicitly yourself ASPNET will perform the default behavior on your behalf

During the PreInit event the target device is determined before the page is initialized the master page is set the control tree is built and the controls are assigned unique IDs which are madeavailable to your code Personalization and themes are loaded and applied to the page in thisstep

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1053

PreInit is the first event in the life cycle that can be trapped and handled That is this is the firstevent that you can write your own code for to change the default behavior of initializing the page

4 During the Init event control properties are read or initialized If this is a postback it isimportant to realize that the controls wonrsquot reflect any changes to the page made before thepostbackthat happens in the PreRender phase They will contain values specified in themarkup file

5 During the Load event all the control properties are set View state information is availableand controls in the pagersquos control hierarchy can be accessed The load phase is routinelymodified in a Page_Load method

6 During the Validation phase the Validate method is called on all the validation controls on thepage The IsValid property is set for all those controls and for the page as a whole

7 During the Rendering phase personalization control and view state is saved Each control onthe page is called in succession to render itself to the browser that is to compose itself intoHTML that is included in the pagersquos Response property

It is very common to handle the PreRender event with a Page_PreRender method typicallywhen you must take some action based on the final value of some other control on the pageDuring the Render event the HTML is actuallygenerated and sent to the requesting pagealthough this event is rarely handled unless you are developing custom controls

8 Unload is the last event of the life cycle It gives you an opportunity to do any final cleanup(ie closing open files and releasing references to expensive resources such as databaseconnections)

During postback the life cycle is the same as during the first load except for the following

1 During the Load phase after initialization is complete the view state and the control state areloaded and applied as necessary

2 After the Validation phase completes postback data is processed Control event handlers arenow executed

This is important control event handlers such as a Button Click are not called until after thePage Initialization and Load events are handled

The following are the various stages a page goes through

Page Request

The request page is either parsed or compiled or fetched from the cache

Start

Page properties like the Request and Response are set The type of request is determined

specifically whether it is a new Request or it is a PostBack Culturing properties are also

determined via the pages ICulture property

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1153

Page Initialization

All the controls on the given page are initialized with a UniqueID (please donrsquot confused

this with the ID property as the UnqiueID is a unique hierarchicial identifier whichincludes the server

controlrsquos naming container) Theming is also applied at this stage

Load

If the current request is a PostBack the data from the viewstate and control state is

loaded to the appropriate properties of the controls

Validation

The Validate method of all the validator controls are fired which in turn sets the Boolean

property IsValid of the controls

Postback Event Handling

If the current request is a PostBack all event handlers are called

Rendering

ViewState data is saved for all the controls that have enabled viewstate The Render

method for all the controls is fired which writes its output to the OutputStream via a text

writer

Unload

Once the page has been rendered and sent the Pagersquos properties are unloaded (cleanup

time)

So know you have a better understanding of the various stages of a ASPNET pages lifecycle you should be aware that within each of the above stages there are events that you

can hook into so that your code is fired at the exact time that you want it to

Event Wire-up is another important concept to understand So Event wire-up is where

ASPNET looks for methods that match a naming convention (eg Page_Load Page_Initetc) and these methods are automatically fired at the appropriate event There is a page

level attribute AutoEventWireup that can be set to either true or false to enable this

behaviour

Below are some of the more popular events that you should understand as you will mostlikely be interested in them

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1253

PreInit

You can use this event to

Create recreate dynamic controls

Set a master page or theme dynamically

Access profile properties

Init

Used to read or initialize your control properties

InitComplete

Used when you need to access your properties after they have been initialized

PreLoad

Used when you need to process things before the Load event has been fired

Load

The Pagersquos OnLoad method and all of its child controlrsquos OnLoad method are firedrecursively This event is used to set properties and make database connections

Control Events

Control specific events are handled at this stage eg Click eventrsquos for the button control

LoadComplete

This stage is for when you need to access controls that have been properly loaded

PreRender

Can be used to make any lsquolast chancersquo changes to the controls before they are rendered

SaveStateComplete

This event is used for things that require view state to be saved yet not making anychanges to the controls themselves

Render

The page object calls this method on all of the controls so all the controls are written andsent to the browser

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1353

Unload

All the controls UnLoad method are fired followed by the pages UnLoad event (bottom-

up) This stage is used for closing database connections closing open files etc

It is import to understand that each server control has its very own life cycle but they arefired recursively so things may not occur at the time you think they do (they occur in

reverse order) What this means is that some events fire from the bottom up like the Init

event while others load from the top-down like the Load event

Purpose

State management is the process by which you maintain state and page information

over multiple requests for the same or different pages

Types of State Management

There are 2 types State Management

1 Client ndash Side State Management This stores information on the clients computer by embedding the information into a

Web page a uniform resource locator(url) or a cookie The techniques available tostore the state information at the client end are listed down below

a View State ndash AspNet uses View State to track the values in the Controls You can

add custom values to the view state It is used by the Aspnet page framework toautomatically save the values of the page and of each control just prior to rendering

to the page When the page is posted one of the first tasks performed by page

processing is to restore view state

b Control State ndash If you create a custom control that requires view state to work

properly you should use control state to ensure other developers donrsquot break yourcontrol by disabling view state

c Hidden fields ndash Like view state hidden fields store data in an HTML form without

displaying it in the users browser The data is available only when the form isprocessed

d Cookies ndash Cookies store a value in the users browser that the browser sends with

every page request to the same server Cookies are the best way to store state datathat must be available for multiple Web pages on a web site

e Query Strings - Query strings store values in the URL that are visible to the userUse query strings when you want a user to be able to e-mail or instant message

state data with a URL

2 Server ndash Side State Management

a Application State - Application State information is available to all pagesregardless of which user requests a page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1453

b Session State ndash Session State information is available to all pages opened by auser during a single visit

Both application state and session state information is lost when the application

restarts To persist user data between application restarts you can store it usingprofile properties

Implementation Procedure

Client ndash Side State Management

View State

The ViewState property provides a dictionary object for retaining values betweenmultiple requests for the same page When an ASPNET page is processed the

current state of the page and controls is hashed into a string and saved in the pageas a hidden field If the data is too long for a single field then ASPNET performs

view state chunking (new in ASPNET 20) to split it across multiple hidden fields

The following code sample demonstrates how view state adds data as a hidden formwithin a Web pagersquos HTML

ltinput type=hidden name=__VIEWSTATE id=__VIEWSTATErdquovalue=wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHnrt75XFpMGnqjqHlH66cdw== gt

Encrypting of the View State You can enable view state encryption to make it more

difficult for attackers and malicious users to directly read view state informationThough this adds processing overhead to the Web server it supports in storing

confidential information in view state To configure view state encryption for an

application does the following

ltConfigurationgt

ltsystemwebgt

ltpages viewStateEncryptionMode=Alwaysgt

ltsystemwebgt

ltconfigurationgt

Alternatively you can enable view state encryption for a specific page by setting thevalue in the page directive as the following sample demonstrates

lt Page Language=C AutoEventWireup=true CodeFile=DefaultaspxcsInherits=_Default ViewStateEncryptionMode=Alwaysgt

View State is enabled by default but if you can disable it by setting the

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1553

EnableViewState property for each web control to false This reduces the serverprocessing time and decreases page size

Reading and Writing Custom View State DataIf you have a value that yoursquod like to keep track of while the user is visiting a single

ASPNET Web page adding a custom value to ViewState is the most efficient andsecure way to do that However ViewState is lost if the user visits a different Web

page so it is useful only for temporarily storing valuesExample Determine the time of last visit to the page

Check if View State object exists and display it if it does

If (ViewState [lastVisit]= null)

Label1Text = (string)ViewState[lastVisit] else

Label1Text = lastVisit ViewState not defined

Define the ViewState object for the next page viewViewStateAdd(lastVisit DateTimeNowToString())

Control State If you create a custom control that requires ViewState you can use

the ControlState property to store state information for your control ControlStateallows you to persist property information that is specific to a control and cannot be

turned off like the ViewState property To use control state in a custom control your

control must override the OnInit method and call the Register-RequiresControlStatemethod during initialization and then override the SaveControl-State and

LoadControlState methods

Hidden fields ViewState stores information in the Web page using hidden fieldsHidden fields are sent back to the server when the user submits a form however

the information is never displayed by the Web browser (unless the user chooses toview the page source) ASPNET allows you to create your own custom hidden fields

and store values that are submitted with other form data A HiddenField controlstores a single variable in its Value property and must be explicitly added to the

page You can use hidden fields only to store information for a single page so it isnot useful for storing session data If you use hidden fields you must submit your

pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which

happens if the user clicks a link) Unlike view state data hidden fields have no built-in compression encryption hashing or chunking so users can view or modify data

stored in hidden fields

Cookies Web applications can store small pieces of data in the clientrsquos Web browserby using cookies A cookie is a small amount of data that is stored either in a text file

on the client file system (if the cookie is persistent) or in memory in the clientbrowser session (if the cookie is temporary) The most common use of cookies is to

identify a single user as he or she visits multiple Web pages

Reading and Writing Cookies

A Web application creates a cookie by sending it to the client as a header in an HTTP

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1653

response The Web browser then submits the same cookie to the server with everynew request

Create a cookie -gt add a value to the ResponseCookies HttpCookieCollectionRead a cookie -gt read values in RequestCookies

Example

Check if cookie exists and display it if it does

if (RequestCookies[lastVisit] = null) Encode the cookie in case thecookie contains client-side script Label1Text =ServerHtmlEncode(RequestCookies[lastVisit]Value)

else Label1Text = No value defined

Define the cookie for the next visit ResponseCookies[lastVisit]Value =DateTimeNowToString()ResponseCookies[lastVisit]Expires =DateTimeNowAddDays(1)

If you do not define the Expires property the browser stores it in memory and the

cookie is lost if the user closes his or her browser

To delete a cookie overwrite the cookie and set an expiration date in the past Youcanrsquot directly delete cookies because they are stored on the clientrsquos computer

Controlling the Cookie Scope By default browsers wonrsquot send a cookie to a Web sitewith a different hostname You can control a cookiersquos scope to either limit the scope

to a specific folder on the Web server or expand the scope to any server in a domainTo limit the scope of a cookie to a folder set the Path property as the following

example demonstrates

Example

ResponseCookies[lastVisit]Path = Application1

Through this the scope is limited to the ldquoApplication1rdquo folder that is the browser

submits the cookie to any page with in this folder and not to pages in other folderseven if the folder is in the same server We can expand the scope to a particular

domain using the following statementExample

ResponseCookies[ldquolastVisitrdquo]Domain = ldquoContosordquo

Storing Multiple Values in a CookieThough it depends on the browser you typically canrsquot store more than 20 cookies

per site and each cookie can be a maximum of 4 KB in length To work around the

20-cookie limit you can store multiple values in a cookie as the following codedemonstratesExample

ResponseCookies[info][visit]Value = DateTimeNowToString()

ResponseCookies[info][firstName]Value = Tony

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 853

HTTP Handlers are the endpoints in the HTTP pipeline All request that are passing

through the HTTPModule should reached to HTTPHandler Then HTTP Handlergenerates the output for the requested resource So when we requesting for any

aspx web pages it returns the corresponding HTML output

All the request now passes from httpModule to respective HTTPHandler then

method and the ASPNET Page life cycle starts This ends the IIS Request processingand start the ASPNET Page Lifecycle

Conclusion

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 953

When client request for some information from a web server request first reaches toHTTPSYS of IIS HTTPSYS then send the request to respective Application Pool

Application Pool then forward the request to worker process to load the ISAPIExtension which will create an HTTPRuntime Object to Process the request via

HTTPModule and HTTPHanlder After that the ASPNET Page LifeCycle events starts

One of the very common question in any dot net interview is aboult explaining ASPNET page lifecycle

ASPNET page life cycle is not very tough to know but in many books I have seen it is written insuch a manner that it seems to be very complicated

In this article I will try to explain the page life cycle as simple as possible

How it all begins

A user sits at her browser and types in a URL A web page appears with text imagesbuttonsand so forth She fills in a text box and clicks a button New data appears in response How doesthis work

When an ASPNET page is requested from the server the server loads the page into server memory processes the page sends the page to the user and then unloads it from memoryFrom the beginning of the life cycle to the end the goal is to render appropriate HTML to therequesting browser At each step methods and events are available that allow you to override thedefault behavior or add your own programmatic enhancements

There are two slightly different sequences in the life cycle one for the first time a page is loadedand a second when the page reloads itself in a postback

During the first page load the life cycle consists of the following steps

1 A request for the page is made from a browser to the web server The ASPNET Frameworkfirst determines whether the page already exists in a cache (a section of memory specificallyreserved for recently used items) If so the page is retrieved and returned to the browser and weare done If not then the actual page life cycle starts at this point

2 During the Start phase the postback mode is determined If the page was requested by adifferent page then it was not a postback If the page was returned to the server for processingand redisplay then it is a postbackThe IsPostBack and PreviousPage properties are set accordingly The Request andResponse properties of the page along with a number of other properties are alsoset

3 The Page Initialization phase contains two events often handled by your codePreInit and InitIf you do not handle these explicitly yourself ASPNET will perform the default behavior on your behalf

During the PreInit event the target device is determined before the page is initialized the master page is set the control tree is built and the controls are assigned unique IDs which are madeavailable to your code Personalization and themes are loaded and applied to the page in thisstep

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1053

PreInit is the first event in the life cycle that can be trapped and handled That is this is the firstevent that you can write your own code for to change the default behavior of initializing the page

4 During the Init event control properties are read or initialized If this is a postback it isimportant to realize that the controls wonrsquot reflect any changes to the page made before thepostbackthat happens in the PreRender phase They will contain values specified in themarkup file

5 During the Load event all the control properties are set View state information is availableand controls in the pagersquos control hierarchy can be accessed The load phase is routinelymodified in a Page_Load method

6 During the Validation phase the Validate method is called on all the validation controls on thepage The IsValid property is set for all those controls and for the page as a whole

7 During the Rendering phase personalization control and view state is saved Each control onthe page is called in succession to render itself to the browser that is to compose itself intoHTML that is included in the pagersquos Response property

It is very common to handle the PreRender event with a Page_PreRender method typicallywhen you must take some action based on the final value of some other control on the pageDuring the Render event the HTML is actuallygenerated and sent to the requesting pagealthough this event is rarely handled unless you are developing custom controls

8 Unload is the last event of the life cycle It gives you an opportunity to do any final cleanup(ie closing open files and releasing references to expensive resources such as databaseconnections)

During postback the life cycle is the same as during the first load except for the following

1 During the Load phase after initialization is complete the view state and the control state areloaded and applied as necessary

2 After the Validation phase completes postback data is processed Control event handlers arenow executed

This is important control event handlers such as a Button Click are not called until after thePage Initialization and Load events are handled

The following are the various stages a page goes through

Page Request

The request page is either parsed or compiled or fetched from the cache

Start

Page properties like the Request and Response are set The type of request is determined

specifically whether it is a new Request or it is a PostBack Culturing properties are also

determined via the pages ICulture property

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1153

Page Initialization

All the controls on the given page are initialized with a UniqueID (please donrsquot confused

this with the ID property as the UnqiueID is a unique hierarchicial identifier whichincludes the server

controlrsquos naming container) Theming is also applied at this stage

Load

If the current request is a PostBack the data from the viewstate and control state is

loaded to the appropriate properties of the controls

Validation

The Validate method of all the validator controls are fired which in turn sets the Boolean

property IsValid of the controls

Postback Event Handling

If the current request is a PostBack all event handlers are called

Rendering

ViewState data is saved for all the controls that have enabled viewstate The Render

method for all the controls is fired which writes its output to the OutputStream via a text

writer

Unload

Once the page has been rendered and sent the Pagersquos properties are unloaded (cleanup

time)

So know you have a better understanding of the various stages of a ASPNET pages lifecycle you should be aware that within each of the above stages there are events that you

can hook into so that your code is fired at the exact time that you want it to

Event Wire-up is another important concept to understand So Event wire-up is where

ASPNET looks for methods that match a naming convention (eg Page_Load Page_Initetc) and these methods are automatically fired at the appropriate event There is a page

level attribute AutoEventWireup that can be set to either true or false to enable this

behaviour

Below are some of the more popular events that you should understand as you will mostlikely be interested in them

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1253

PreInit

You can use this event to

Create recreate dynamic controls

Set a master page or theme dynamically

Access profile properties

Init

Used to read or initialize your control properties

InitComplete

Used when you need to access your properties after they have been initialized

PreLoad

Used when you need to process things before the Load event has been fired

Load

The Pagersquos OnLoad method and all of its child controlrsquos OnLoad method are firedrecursively This event is used to set properties and make database connections

Control Events

Control specific events are handled at this stage eg Click eventrsquos for the button control

LoadComplete

This stage is for when you need to access controls that have been properly loaded

PreRender

Can be used to make any lsquolast chancersquo changes to the controls before they are rendered

SaveStateComplete

This event is used for things that require view state to be saved yet not making anychanges to the controls themselves

Render

The page object calls this method on all of the controls so all the controls are written andsent to the browser

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1353

Unload

All the controls UnLoad method are fired followed by the pages UnLoad event (bottom-

up) This stage is used for closing database connections closing open files etc

It is import to understand that each server control has its very own life cycle but they arefired recursively so things may not occur at the time you think they do (they occur in

reverse order) What this means is that some events fire from the bottom up like the Init

event while others load from the top-down like the Load event

Purpose

State management is the process by which you maintain state and page information

over multiple requests for the same or different pages

Types of State Management

There are 2 types State Management

1 Client ndash Side State Management This stores information on the clients computer by embedding the information into a

Web page a uniform resource locator(url) or a cookie The techniques available tostore the state information at the client end are listed down below

a View State ndash AspNet uses View State to track the values in the Controls You can

add custom values to the view state It is used by the Aspnet page framework toautomatically save the values of the page and of each control just prior to rendering

to the page When the page is posted one of the first tasks performed by page

processing is to restore view state

b Control State ndash If you create a custom control that requires view state to work

properly you should use control state to ensure other developers donrsquot break yourcontrol by disabling view state

c Hidden fields ndash Like view state hidden fields store data in an HTML form without

displaying it in the users browser The data is available only when the form isprocessed

d Cookies ndash Cookies store a value in the users browser that the browser sends with

every page request to the same server Cookies are the best way to store state datathat must be available for multiple Web pages on a web site

e Query Strings - Query strings store values in the URL that are visible to the userUse query strings when you want a user to be able to e-mail or instant message

state data with a URL

2 Server ndash Side State Management

a Application State - Application State information is available to all pagesregardless of which user requests a page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1453

b Session State ndash Session State information is available to all pages opened by auser during a single visit

Both application state and session state information is lost when the application

restarts To persist user data between application restarts you can store it usingprofile properties

Implementation Procedure

Client ndash Side State Management

View State

The ViewState property provides a dictionary object for retaining values betweenmultiple requests for the same page When an ASPNET page is processed the

current state of the page and controls is hashed into a string and saved in the pageas a hidden field If the data is too long for a single field then ASPNET performs

view state chunking (new in ASPNET 20) to split it across multiple hidden fields

The following code sample demonstrates how view state adds data as a hidden formwithin a Web pagersquos HTML

ltinput type=hidden name=__VIEWSTATE id=__VIEWSTATErdquovalue=wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHnrt75XFpMGnqjqHlH66cdw== gt

Encrypting of the View State You can enable view state encryption to make it more

difficult for attackers and malicious users to directly read view state informationThough this adds processing overhead to the Web server it supports in storing

confidential information in view state To configure view state encryption for an

application does the following

ltConfigurationgt

ltsystemwebgt

ltpages viewStateEncryptionMode=Alwaysgt

ltsystemwebgt

ltconfigurationgt

Alternatively you can enable view state encryption for a specific page by setting thevalue in the page directive as the following sample demonstrates

lt Page Language=C AutoEventWireup=true CodeFile=DefaultaspxcsInherits=_Default ViewStateEncryptionMode=Alwaysgt

View State is enabled by default but if you can disable it by setting the

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1553

EnableViewState property for each web control to false This reduces the serverprocessing time and decreases page size

Reading and Writing Custom View State DataIf you have a value that yoursquod like to keep track of while the user is visiting a single

ASPNET Web page adding a custom value to ViewState is the most efficient andsecure way to do that However ViewState is lost if the user visits a different Web

page so it is useful only for temporarily storing valuesExample Determine the time of last visit to the page

Check if View State object exists and display it if it does

If (ViewState [lastVisit]= null)

Label1Text = (string)ViewState[lastVisit] else

Label1Text = lastVisit ViewState not defined

Define the ViewState object for the next page viewViewStateAdd(lastVisit DateTimeNowToString())

Control State If you create a custom control that requires ViewState you can use

the ControlState property to store state information for your control ControlStateallows you to persist property information that is specific to a control and cannot be

turned off like the ViewState property To use control state in a custom control your

control must override the OnInit method and call the Register-RequiresControlStatemethod during initialization and then override the SaveControl-State and

LoadControlState methods

Hidden fields ViewState stores information in the Web page using hidden fieldsHidden fields are sent back to the server when the user submits a form however

the information is never displayed by the Web browser (unless the user chooses toview the page source) ASPNET allows you to create your own custom hidden fields

and store values that are submitted with other form data A HiddenField controlstores a single variable in its Value property and must be explicitly added to the

page You can use hidden fields only to store information for a single page so it isnot useful for storing session data If you use hidden fields you must submit your

pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which

happens if the user clicks a link) Unlike view state data hidden fields have no built-in compression encryption hashing or chunking so users can view or modify data

stored in hidden fields

Cookies Web applications can store small pieces of data in the clientrsquos Web browserby using cookies A cookie is a small amount of data that is stored either in a text file

on the client file system (if the cookie is persistent) or in memory in the clientbrowser session (if the cookie is temporary) The most common use of cookies is to

identify a single user as he or she visits multiple Web pages

Reading and Writing Cookies

A Web application creates a cookie by sending it to the client as a header in an HTTP

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1653

response The Web browser then submits the same cookie to the server with everynew request

Create a cookie -gt add a value to the ResponseCookies HttpCookieCollectionRead a cookie -gt read values in RequestCookies

Example

Check if cookie exists and display it if it does

if (RequestCookies[lastVisit] = null) Encode the cookie in case thecookie contains client-side script Label1Text =ServerHtmlEncode(RequestCookies[lastVisit]Value)

else Label1Text = No value defined

Define the cookie for the next visit ResponseCookies[lastVisit]Value =DateTimeNowToString()ResponseCookies[lastVisit]Expires =DateTimeNowAddDays(1)

If you do not define the Expires property the browser stores it in memory and the

cookie is lost if the user closes his or her browser

To delete a cookie overwrite the cookie and set an expiration date in the past Youcanrsquot directly delete cookies because they are stored on the clientrsquos computer

Controlling the Cookie Scope By default browsers wonrsquot send a cookie to a Web sitewith a different hostname You can control a cookiersquos scope to either limit the scope

to a specific folder on the Web server or expand the scope to any server in a domainTo limit the scope of a cookie to a folder set the Path property as the following

example demonstrates

Example

ResponseCookies[lastVisit]Path = Application1

Through this the scope is limited to the ldquoApplication1rdquo folder that is the browser

submits the cookie to any page with in this folder and not to pages in other folderseven if the folder is in the same server We can expand the scope to a particular

domain using the following statementExample

ResponseCookies[ldquolastVisitrdquo]Domain = ldquoContosordquo

Storing Multiple Values in a CookieThough it depends on the browser you typically canrsquot store more than 20 cookies

per site and each cookie can be a maximum of 4 KB in length To work around the

20-cookie limit you can store multiple values in a cookie as the following codedemonstratesExample

ResponseCookies[info][visit]Value = DateTimeNowToString()

ResponseCookies[info][firstName]Value = Tony

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 953

When client request for some information from a web server request first reaches toHTTPSYS of IIS HTTPSYS then send the request to respective Application Pool

Application Pool then forward the request to worker process to load the ISAPIExtension which will create an HTTPRuntime Object to Process the request via

HTTPModule and HTTPHanlder After that the ASPNET Page LifeCycle events starts

One of the very common question in any dot net interview is aboult explaining ASPNET page lifecycle

ASPNET page life cycle is not very tough to know but in many books I have seen it is written insuch a manner that it seems to be very complicated

In this article I will try to explain the page life cycle as simple as possible

How it all begins

A user sits at her browser and types in a URL A web page appears with text imagesbuttonsand so forth She fills in a text box and clicks a button New data appears in response How doesthis work

When an ASPNET page is requested from the server the server loads the page into server memory processes the page sends the page to the user and then unloads it from memoryFrom the beginning of the life cycle to the end the goal is to render appropriate HTML to therequesting browser At each step methods and events are available that allow you to override thedefault behavior or add your own programmatic enhancements

There are two slightly different sequences in the life cycle one for the first time a page is loadedand a second when the page reloads itself in a postback

During the first page load the life cycle consists of the following steps

1 A request for the page is made from a browser to the web server The ASPNET Frameworkfirst determines whether the page already exists in a cache (a section of memory specificallyreserved for recently used items) If so the page is retrieved and returned to the browser and weare done If not then the actual page life cycle starts at this point

2 During the Start phase the postback mode is determined If the page was requested by adifferent page then it was not a postback If the page was returned to the server for processingand redisplay then it is a postbackThe IsPostBack and PreviousPage properties are set accordingly The Request andResponse properties of the page along with a number of other properties are alsoset

3 The Page Initialization phase contains two events often handled by your codePreInit and InitIf you do not handle these explicitly yourself ASPNET will perform the default behavior on your behalf

During the PreInit event the target device is determined before the page is initialized the master page is set the control tree is built and the controls are assigned unique IDs which are madeavailable to your code Personalization and themes are loaded and applied to the page in thisstep

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1053

PreInit is the first event in the life cycle that can be trapped and handled That is this is the firstevent that you can write your own code for to change the default behavior of initializing the page

4 During the Init event control properties are read or initialized If this is a postback it isimportant to realize that the controls wonrsquot reflect any changes to the page made before thepostbackthat happens in the PreRender phase They will contain values specified in themarkup file

5 During the Load event all the control properties are set View state information is availableand controls in the pagersquos control hierarchy can be accessed The load phase is routinelymodified in a Page_Load method

6 During the Validation phase the Validate method is called on all the validation controls on thepage The IsValid property is set for all those controls and for the page as a whole

7 During the Rendering phase personalization control and view state is saved Each control onthe page is called in succession to render itself to the browser that is to compose itself intoHTML that is included in the pagersquos Response property

It is very common to handle the PreRender event with a Page_PreRender method typicallywhen you must take some action based on the final value of some other control on the pageDuring the Render event the HTML is actuallygenerated and sent to the requesting pagealthough this event is rarely handled unless you are developing custom controls

8 Unload is the last event of the life cycle It gives you an opportunity to do any final cleanup(ie closing open files and releasing references to expensive resources such as databaseconnections)

During postback the life cycle is the same as during the first load except for the following

1 During the Load phase after initialization is complete the view state and the control state areloaded and applied as necessary

2 After the Validation phase completes postback data is processed Control event handlers arenow executed

This is important control event handlers such as a Button Click are not called until after thePage Initialization and Load events are handled

The following are the various stages a page goes through

Page Request

The request page is either parsed or compiled or fetched from the cache

Start

Page properties like the Request and Response are set The type of request is determined

specifically whether it is a new Request or it is a PostBack Culturing properties are also

determined via the pages ICulture property

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1153

Page Initialization

All the controls on the given page are initialized with a UniqueID (please donrsquot confused

this with the ID property as the UnqiueID is a unique hierarchicial identifier whichincludes the server

controlrsquos naming container) Theming is also applied at this stage

Load

If the current request is a PostBack the data from the viewstate and control state is

loaded to the appropriate properties of the controls

Validation

The Validate method of all the validator controls are fired which in turn sets the Boolean

property IsValid of the controls

Postback Event Handling

If the current request is a PostBack all event handlers are called

Rendering

ViewState data is saved for all the controls that have enabled viewstate The Render

method for all the controls is fired which writes its output to the OutputStream via a text

writer

Unload

Once the page has been rendered and sent the Pagersquos properties are unloaded (cleanup

time)

So know you have a better understanding of the various stages of a ASPNET pages lifecycle you should be aware that within each of the above stages there are events that you

can hook into so that your code is fired at the exact time that you want it to

Event Wire-up is another important concept to understand So Event wire-up is where

ASPNET looks for methods that match a naming convention (eg Page_Load Page_Initetc) and these methods are automatically fired at the appropriate event There is a page

level attribute AutoEventWireup that can be set to either true or false to enable this

behaviour

Below are some of the more popular events that you should understand as you will mostlikely be interested in them

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1253

PreInit

You can use this event to

Create recreate dynamic controls

Set a master page or theme dynamically

Access profile properties

Init

Used to read or initialize your control properties

InitComplete

Used when you need to access your properties after they have been initialized

PreLoad

Used when you need to process things before the Load event has been fired

Load

The Pagersquos OnLoad method and all of its child controlrsquos OnLoad method are firedrecursively This event is used to set properties and make database connections

Control Events

Control specific events are handled at this stage eg Click eventrsquos for the button control

LoadComplete

This stage is for when you need to access controls that have been properly loaded

PreRender

Can be used to make any lsquolast chancersquo changes to the controls before they are rendered

SaveStateComplete

This event is used for things that require view state to be saved yet not making anychanges to the controls themselves

Render

The page object calls this method on all of the controls so all the controls are written andsent to the browser

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1353

Unload

All the controls UnLoad method are fired followed by the pages UnLoad event (bottom-

up) This stage is used for closing database connections closing open files etc

It is import to understand that each server control has its very own life cycle but they arefired recursively so things may not occur at the time you think they do (they occur in

reverse order) What this means is that some events fire from the bottom up like the Init

event while others load from the top-down like the Load event

Purpose

State management is the process by which you maintain state and page information

over multiple requests for the same or different pages

Types of State Management

There are 2 types State Management

1 Client ndash Side State Management This stores information on the clients computer by embedding the information into a

Web page a uniform resource locator(url) or a cookie The techniques available tostore the state information at the client end are listed down below

a View State ndash AspNet uses View State to track the values in the Controls You can

add custom values to the view state It is used by the Aspnet page framework toautomatically save the values of the page and of each control just prior to rendering

to the page When the page is posted one of the first tasks performed by page

processing is to restore view state

b Control State ndash If you create a custom control that requires view state to work

properly you should use control state to ensure other developers donrsquot break yourcontrol by disabling view state

c Hidden fields ndash Like view state hidden fields store data in an HTML form without

displaying it in the users browser The data is available only when the form isprocessed

d Cookies ndash Cookies store a value in the users browser that the browser sends with

every page request to the same server Cookies are the best way to store state datathat must be available for multiple Web pages on a web site

e Query Strings - Query strings store values in the URL that are visible to the userUse query strings when you want a user to be able to e-mail or instant message

state data with a URL

2 Server ndash Side State Management

a Application State - Application State information is available to all pagesregardless of which user requests a page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1453

b Session State ndash Session State information is available to all pages opened by auser during a single visit

Both application state and session state information is lost when the application

restarts To persist user data between application restarts you can store it usingprofile properties

Implementation Procedure

Client ndash Side State Management

View State

The ViewState property provides a dictionary object for retaining values betweenmultiple requests for the same page When an ASPNET page is processed the

current state of the page and controls is hashed into a string and saved in the pageas a hidden field If the data is too long for a single field then ASPNET performs

view state chunking (new in ASPNET 20) to split it across multiple hidden fields

The following code sample demonstrates how view state adds data as a hidden formwithin a Web pagersquos HTML

ltinput type=hidden name=__VIEWSTATE id=__VIEWSTATErdquovalue=wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHnrt75XFpMGnqjqHlH66cdw== gt

Encrypting of the View State You can enable view state encryption to make it more

difficult for attackers and malicious users to directly read view state informationThough this adds processing overhead to the Web server it supports in storing

confidential information in view state To configure view state encryption for an

application does the following

ltConfigurationgt

ltsystemwebgt

ltpages viewStateEncryptionMode=Alwaysgt

ltsystemwebgt

ltconfigurationgt

Alternatively you can enable view state encryption for a specific page by setting thevalue in the page directive as the following sample demonstrates

lt Page Language=C AutoEventWireup=true CodeFile=DefaultaspxcsInherits=_Default ViewStateEncryptionMode=Alwaysgt

View State is enabled by default but if you can disable it by setting the

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1553

EnableViewState property for each web control to false This reduces the serverprocessing time and decreases page size

Reading and Writing Custom View State DataIf you have a value that yoursquod like to keep track of while the user is visiting a single

ASPNET Web page adding a custom value to ViewState is the most efficient andsecure way to do that However ViewState is lost if the user visits a different Web

page so it is useful only for temporarily storing valuesExample Determine the time of last visit to the page

Check if View State object exists and display it if it does

If (ViewState [lastVisit]= null)

Label1Text = (string)ViewState[lastVisit] else

Label1Text = lastVisit ViewState not defined

Define the ViewState object for the next page viewViewStateAdd(lastVisit DateTimeNowToString())

Control State If you create a custom control that requires ViewState you can use

the ControlState property to store state information for your control ControlStateallows you to persist property information that is specific to a control and cannot be

turned off like the ViewState property To use control state in a custom control your

control must override the OnInit method and call the Register-RequiresControlStatemethod during initialization and then override the SaveControl-State and

LoadControlState methods

Hidden fields ViewState stores information in the Web page using hidden fieldsHidden fields are sent back to the server when the user submits a form however

the information is never displayed by the Web browser (unless the user chooses toview the page source) ASPNET allows you to create your own custom hidden fields

and store values that are submitted with other form data A HiddenField controlstores a single variable in its Value property and must be explicitly added to the

page You can use hidden fields only to store information for a single page so it isnot useful for storing session data If you use hidden fields you must submit your

pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which

happens if the user clicks a link) Unlike view state data hidden fields have no built-in compression encryption hashing or chunking so users can view or modify data

stored in hidden fields

Cookies Web applications can store small pieces of data in the clientrsquos Web browserby using cookies A cookie is a small amount of data that is stored either in a text file

on the client file system (if the cookie is persistent) or in memory in the clientbrowser session (if the cookie is temporary) The most common use of cookies is to

identify a single user as he or she visits multiple Web pages

Reading and Writing Cookies

A Web application creates a cookie by sending it to the client as a header in an HTTP

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1653

response The Web browser then submits the same cookie to the server with everynew request

Create a cookie -gt add a value to the ResponseCookies HttpCookieCollectionRead a cookie -gt read values in RequestCookies

Example

Check if cookie exists and display it if it does

if (RequestCookies[lastVisit] = null) Encode the cookie in case thecookie contains client-side script Label1Text =ServerHtmlEncode(RequestCookies[lastVisit]Value)

else Label1Text = No value defined

Define the cookie for the next visit ResponseCookies[lastVisit]Value =DateTimeNowToString()ResponseCookies[lastVisit]Expires =DateTimeNowAddDays(1)

If you do not define the Expires property the browser stores it in memory and the

cookie is lost if the user closes his or her browser

To delete a cookie overwrite the cookie and set an expiration date in the past Youcanrsquot directly delete cookies because they are stored on the clientrsquos computer

Controlling the Cookie Scope By default browsers wonrsquot send a cookie to a Web sitewith a different hostname You can control a cookiersquos scope to either limit the scope

to a specific folder on the Web server or expand the scope to any server in a domainTo limit the scope of a cookie to a folder set the Path property as the following

example demonstrates

Example

ResponseCookies[lastVisit]Path = Application1

Through this the scope is limited to the ldquoApplication1rdquo folder that is the browser

submits the cookie to any page with in this folder and not to pages in other folderseven if the folder is in the same server We can expand the scope to a particular

domain using the following statementExample

ResponseCookies[ldquolastVisitrdquo]Domain = ldquoContosordquo

Storing Multiple Values in a CookieThough it depends on the browser you typically canrsquot store more than 20 cookies

per site and each cookie can be a maximum of 4 KB in length To work around the

20-cookie limit you can store multiple values in a cookie as the following codedemonstratesExample

ResponseCookies[info][visit]Value = DateTimeNowToString()

ResponseCookies[info][firstName]Value = Tony

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1053

PreInit is the first event in the life cycle that can be trapped and handled That is this is the firstevent that you can write your own code for to change the default behavior of initializing the page

4 During the Init event control properties are read or initialized If this is a postback it isimportant to realize that the controls wonrsquot reflect any changes to the page made before thepostbackthat happens in the PreRender phase They will contain values specified in themarkup file

5 During the Load event all the control properties are set View state information is availableand controls in the pagersquos control hierarchy can be accessed The load phase is routinelymodified in a Page_Load method

6 During the Validation phase the Validate method is called on all the validation controls on thepage The IsValid property is set for all those controls and for the page as a whole

7 During the Rendering phase personalization control and view state is saved Each control onthe page is called in succession to render itself to the browser that is to compose itself intoHTML that is included in the pagersquos Response property

It is very common to handle the PreRender event with a Page_PreRender method typicallywhen you must take some action based on the final value of some other control on the pageDuring the Render event the HTML is actuallygenerated and sent to the requesting pagealthough this event is rarely handled unless you are developing custom controls

8 Unload is the last event of the life cycle It gives you an opportunity to do any final cleanup(ie closing open files and releasing references to expensive resources such as databaseconnections)

During postback the life cycle is the same as during the first load except for the following

1 During the Load phase after initialization is complete the view state and the control state areloaded and applied as necessary

2 After the Validation phase completes postback data is processed Control event handlers arenow executed

This is important control event handlers such as a Button Click are not called until after thePage Initialization and Load events are handled

The following are the various stages a page goes through

Page Request

The request page is either parsed or compiled or fetched from the cache

Start

Page properties like the Request and Response are set The type of request is determined

specifically whether it is a new Request or it is a PostBack Culturing properties are also

determined via the pages ICulture property

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1153

Page Initialization

All the controls on the given page are initialized with a UniqueID (please donrsquot confused

this with the ID property as the UnqiueID is a unique hierarchicial identifier whichincludes the server

controlrsquos naming container) Theming is also applied at this stage

Load

If the current request is a PostBack the data from the viewstate and control state is

loaded to the appropriate properties of the controls

Validation

The Validate method of all the validator controls are fired which in turn sets the Boolean

property IsValid of the controls

Postback Event Handling

If the current request is a PostBack all event handlers are called

Rendering

ViewState data is saved for all the controls that have enabled viewstate The Render

method for all the controls is fired which writes its output to the OutputStream via a text

writer

Unload

Once the page has been rendered and sent the Pagersquos properties are unloaded (cleanup

time)

So know you have a better understanding of the various stages of a ASPNET pages lifecycle you should be aware that within each of the above stages there are events that you

can hook into so that your code is fired at the exact time that you want it to

Event Wire-up is another important concept to understand So Event wire-up is where

ASPNET looks for methods that match a naming convention (eg Page_Load Page_Initetc) and these methods are automatically fired at the appropriate event There is a page

level attribute AutoEventWireup that can be set to either true or false to enable this

behaviour

Below are some of the more popular events that you should understand as you will mostlikely be interested in them

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1253

PreInit

You can use this event to

Create recreate dynamic controls

Set a master page or theme dynamically

Access profile properties

Init

Used to read or initialize your control properties

InitComplete

Used when you need to access your properties after they have been initialized

PreLoad

Used when you need to process things before the Load event has been fired

Load

The Pagersquos OnLoad method and all of its child controlrsquos OnLoad method are firedrecursively This event is used to set properties and make database connections

Control Events

Control specific events are handled at this stage eg Click eventrsquos for the button control

LoadComplete

This stage is for when you need to access controls that have been properly loaded

PreRender

Can be used to make any lsquolast chancersquo changes to the controls before they are rendered

SaveStateComplete

This event is used for things that require view state to be saved yet not making anychanges to the controls themselves

Render

The page object calls this method on all of the controls so all the controls are written andsent to the browser

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1353

Unload

All the controls UnLoad method are fired followed by the pages UnLoad event (bottom-

up) This stage is used for closing database connections closing open files etc

It is import to understand that each server control has its very own life cycle but they arefired recursively so things may not occur at the time you think they do (they occur in

reverse order) What this means is that some events fire from the bottom up like the Init

event while others load from the top-down like the Load event

Purpose

State management is the process by which you maintain state and page information

over multiple requests for the same or different pages

Types of State Management

There are 2 types State Management

1 Client ndash Side State Management This stores information on the clients computer by embedding the information into a

Web page a uniform resource locator(url) or a cookie The techniques available tostore the state information at the client end are listed down below

a View State ndash AspNet uses View State to track the values in the Controls You can

add custom values to the view state It is used by the Aspnet page framework toautomatically save the values of the page and of each control just prior to rendering

to the page When the page is posted one of the first tasks performed by page

processing is to restore view state

b Control State ndash If you create a custom control that requires view state to work

properly you should use control state to ensure other developers donrsquot break yourcontrol by disabling view state

c Hidden fields ndash Like view state hidden fields store data in an HTML form without

displaying it in the users browser The data is available only when the form isprocessed

d Cookies ndash Cookies store a value in the users browser that the browser sends with

every page request to the same server Cookies are the best way to store state datathat must be available for multiple Web pages on a web site

e Query Strings - Query strings store values in the URL that are visible to the userUse query strings when you want a user to be able to e-mail or instant message

state data with a URL

2 Server ndash Side State Management

a Application State - Application State information is available to all pagesregardless of which user requests a page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1453

b Session State ndash Session State information is available to all pages opened by auser during a single visit

Both application state and session state information is lost when the application

restarts To persist user data between application restarts you can store it usingprofile properties

Implementation Procedure

Client ndash Side State Management

View State

The ViewState property provides a dictionary object for retaining values betweenmultiple requests for the same page When an ASPNET page is processed the

current state of the page and controls is hashed into a string and saved in the pageas a hidden field If the data is too long for a single field then ASPNET performs

view state chunking (new in ASPNET 20) to split it across multiple hidden fields

The following code sample demonstrates how view state adds data as a hidden formwithin a Web pagersquos HTML

ltinput type=hidden name=__VIEWSTATE id=__VIEWSTATErdquovalue=wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHnrt75XFpMGnqjqHlH66cdw== gt

Encrypting of the View State You can enable view state encryption to make it more

difficult for attackers and malicious users to directly read view state informationThough this adds processing overhead to the Web server it supports in storing

confidential information in view state To configure view state encryption for an

application does the following

ltConfigurationgt

ltsystemwebgt

ltpages viewStateEncryptionMode=Alwaysgt

ltsystemwebgt

ltconfigurationgt

Alternatively you can enable view state encryption for a specific page by setting thevalue in the page directive as the following sample demonstrates

lt Page Language=C AutoEventWireup=true CodeFile=DefaultaspxcsInherits=_Default ViewStateEncryptionMode=Alwaysgt

View State is enabled by default but if you can disable it by setting the

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1553

EnableViewState property for each web control to false This reduces the serverprocessing time and decreases page size

Reading and Writing Custom View State DataIf you have a value that yoursquod like to keep track of while the user is visiting a single

ASPNET Web page adding a custom value to ViewState is the most efficient andsecure way to do that However ViewState is lost if the user visits a different Web

page so it is useful only for temporarily storing valuesExample Determine the time of last visit to the page

Check if View State object exists and display it if it does

If (ViewState [lastVisit]= null)

Label1Text = (string)ViewState[lastVisit] else

Label1Text = lastVisit ViewState not defined

Define the ViewState object for the next page viewViewStateAdd(lastVisit DateTimeNowToString())

Control State If you create a custom control that requires ViewState you can use

the ControlState property to store state information for your control ControlStateallows you to persist property information that is specific to a control and cannot be

turned off like the ViewState property To use control state in a custom control your

control must override the OnInit method and call the Register-RequiresControlStatemethod during initialization and then override the SaveControl-State and

LoadControlState methods

Hidden fields ViewState stores information in the Web page using hidden fieldsHidden fields are sent back to the server when the user submits a form however

the information is never displayed by the Web browser (unless the user chooses toview the page source) ASPNET allows you to create your own custom hidden fields

and store values that are submitted with other form data A HiddenField controlstores a single variable in its Value property and must be explicitly added to the

page You can use hidden fields only to store information for a single page so it isnot useful for storing session data If you use hidden fields you must submit your

pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which

happens if the user clicks a link) Unlike view state data hidden fields have no built-in compression encryption hashing or chunking so users can view or modify data

stored in hidden fields

Cookies Web applications can store small pieces of data in the clientrsquos Web browserby using cookies A cookie is a small amount of data that is stored either in a text file

on the client file system (if the cookie is persistent) or in memory in the clientbrowser session (if the cookie is temporary) The most common use of cookies is to

identify a single user as he or she visits multiple Web pages

Reading and Writing Cookies

A Web application creates a cookie by sending it to the client as a header in an HTTP

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1653

response The Web browser then submits the same cookie to the server with everynew request

Create a cookie -gt add a value to the ResponseCookies HttpCookieCollectionRead a cookie -gt read values in RequestCookies

Example

Check if cookie exists and display it if it does

if (RequestCookies[lastVisit] = null) Encode the cookie in case thecookie contains client-side script Label1Text =ServerHtmlEncode(RequestCookies[lastVisit]Value)

else Label1Text = No value defined

Define the cookie for the next visit ResponseCookies[lastVisit]Value =DateTimeNowToString()ResponseCookies[lastVisit]Expires =DateTimeNowAddDays(1)

If you do not define the Expires property the browser stores it in memory and the

cookie is lost if the user closes his or her browser

To delete a cookie overwrite the cookie and set an expiration date in the past Youcanrsquot directly delete cookies because they are stored on the clientrsquos computer

Controlling the Cookie Scope By default browsers wonrsquot send a cookie to a Web sitewith a different hostname You can control a cookiersquos scope to either limit the scope

to a specific folder on the Web server or expand the scope to any server in a domainTo limit the scope of a cookie to a folder set the Path property as the following

example demonstrates

Example

ResponseCookies[lastVisit]Path = Application1

Through this the scope is limited to the ldquoApplication1rdquo folder that is the browser

submits the cookie to any page with in this folder and not to pages in other folderseven if the folder is in the same server We can expand the scope to a particular

domain using the following statementExample

ResponseCookies[ldquolastVisitrdquo]Domain = ldquoContosordquo

Storing Multiple Values in a CookieThough it depends on the browser you typically canrsquot store more than 20 cookies

per site and each cookie can be a maximum of 4 KB in length To work around the

20-cookie limit you can store multiple values in a cookie as the following codedemonstratesExample

ResponseCookies[info][visit]Value = DateTimeNowToString()

ResponseCookies[info][firstName]Value = Tony

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1153

Page Initialization

All the controls on the given page are initialized with a UniqueID (please donrsquot confused

this with the ID property as the UnqiueID is a unique hierarchicial identifier whichincludes the server

controlrsquos naming container) Theming is also applied at this stage

Load

If the current request is a PostBack the data from the viewstate and control state is

loaded to the appropriate properties of the controls

Validation

The Validate method of all the validator controls are fired which in turn sets the Boolean

property IsValid of the controls

Postback Event Handling

If the current request is a PostBack all event handlers are called

Rendering

ViewState data is saved for all the controls that have enabled viewstate The Render

method for all the controls is fired which writes its output to the OutputStream via a text

writer

Unload

Once the page has been rendered and sent the Pagersquos properties are unloaded (cleanup

time)

So know you have a better understanding of the various stages of a ASPNET pages lifecycle you should be aware that within each of the above stages there are events that you

can hook into so that your code is fired at the exact time that you want it to

Event Wire-up is another important concept to understand So Event wire-up is where

ASPNET looks for methods that match a naming convention (eg Page_Load Page_Initetc) and these methods are automatically fired at the appropriate event There is a page

level attribute AutoEventWireup that can be set to either true or false to enable this

behaviour

Below are some of the more popular events that you should understand as you will mostlikely be interested in them

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1253

PreInit

You can use this event to

Create recreate dynamic controls

Set a master page or theme dynamically

Access profile properties

Init

Used to read or initialize your control properties

InitComplete

Used when you need to access your properties after they have been initialized

PreLoad

Used when you need to process things before the Load event has been fired

Load

The Pagersquos OnLoad method and all of its child controlrsquos OnLoad method are firedrecursively This event is used to set properties and make database connections

Control Events

Control specific events are handled at this stage eg Click eventrsquos for the button control

LoadComplete

This stage is for when you need to access controls that have been properly loaded

PreRender

Can be used to make any lsquolast chancersquo changes to the controls before they are rendered

SaveStateComplete

This event is used for things that require view state to be saved yet not making anychanges to the controls themselves

Render

The page object calls this method on all of the controls so all the controls are written andsent to the browser

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1353

Unload

All the controls UnLoad method are fired followed by the pages UnLoad event (bottom-

up) This stage is used for closing database connections closing open files etc

It is import to understand that each server control has its very own life cycle but they arefired recursively so things may not occur at the time you think they do (they occur in

reverse order) What this means is that some events fire from the bottom up like the Init

event while others load from the top-down like the Load event

Purpose

State management is the process by which you maintain state and page information

over multiple requests for the same or different pages

Types of State Management

There are 2 types State Management

1 Client ndash Side State Management This stores information on the clients computer by embedding the information into a

Web page a uniform resource locator(url) or a cookie The techniques available tostore the state information at the client end are listed down below

a View State ndash AspNet uses View State to track the values in the Controls You can

add custom values to the view state It is used by the Aspnet page framework toautomatically save the values of the page and of each control just prior to rendering

to the page When the page is posted one of the first tasks performed by page

processing is to restore view state

b Control State ndash If you create a custom control that requires view state to work

properly you should use control state to ensure other developers donrsquot break yourcontrol by disabling view state

c Hidden fields ndash Like view state hidden fields store data in an HTML form without

displaying it in the users browser The data is available only when the form isprocessed

d Cookies ndash Cookies store a value in the users browser that the browser sends with

every page request to the same server Cookies are the best way to store state datathat must be available for multiple Web pages on a web site

e Query Strings - Query strings store values in the URL that are visible to the userUse query strings when you want a user to be able to e-mail or instant message

state data with a URL

2 Server ndash Side State Management

a Application State - Application State information is available to all pagesregardless of which user requests a page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1453

b Session State ndash Session State information is available to all pages opened by auser during a single visit

Both application state and session state information is lost when the application

restarts To persist user data between application restarts you can store it usingprofile properties

Implementation Procedure

Client ndash Side State Management

View State

The ViewState property provides a dictionary object for retaining values betweenmultiple requests for the same page When an ASPNET page is processed the

current state of the page and controls is hashed into a string and saved in the pageas a hidden field If the data is too long for a single field then ASPNET performs

view state chunking (new in ASPNET 20) to split it across multiple hidden fields

The following code sample demonstrates how view state adds data as a hidden formwithin a Web pagersquos HTML

ltinput type=hidden name=__VIEWSTATE id=__VIEWSTATErdquovalue=wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHnrt75XFpMGnqjqHlH66cdw== gt

Encrypting of the View State You can enable view state encryption to make it more

difficult for attackers and malicious users to directly read view state informationThough this adds processing overhead to the Web server it supports in storing

confidential information in view state To configure view state encryption for an

application does the following

ltConfigurationgt

ltsystemwebgt

ltpages viewStateEncryptionMode=Alwaysgt

ltsystemwebgt

ltconfigurationgt

Alternatively you can enable view state encryption for a specific page by setting thevalue in the page directive as the following sample demonstrates

lt Page Language=C AutoEventWireup=true CodeFile=DefaultaspxcsInherits=_Default ViewStateEncryptionMode=Alwaysgt

View State is enabled by default but if you can disable it by setting the

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1553

EnableViewState property for each web control to false This reduces the serverprocessing time and decreases page size

Reading and Writing Custom View State DataIf you have a value that yoursquod like to keep track of while the user is visiting a single

ASPNET Web page adding a custom value to ViewState is the most efficient andsecure way to do that However ViewState is lost if the user visits a different Web

page so it is useful only for temporarily storing valuesExample Determine the time of last visit to the page

Check if View State object exists and display it if it does

If (ViewState [lastVisit]= null)

Label1Text = (string)ViewState[lastVisit] else

Label1Text = lastVisit ViewState not defined

Define the ViewState object for the next page viewViewStateAdd(lastVisit DateTimeNowToString())

Control State If you create a custom control that requires ViewState you can use

the ControlState property to store state information for your control ControlStateallows you to persist property information that is specific to a control and cannot be

turned off like the ViewState property To use control state in a custom control your

control must override the OnInit method and call the Register-RequiresControlStatemethod during initialization and then override the SaveControl-State and

LoadControlState methods

Hidden fields ViewState stores information in the Web page using hidden fieldsHidden fields are sent back to the server when the user submits a form however

the information is never displayed by the Web browser (unless the user chooses toview the page source) ASPNET allows you to create your own custom hidden fields

and store values that are submitted with other form data A HiddenField controlstores a single variable in its Value property and must be explicitly added to the

page You can use hidden fields only to store information for a single page so it isnot useful for storing session data If you use hidden fields you must submit your

pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which

happens if the user clicks a link) Unlike view state data hidden fields have no built-in compression encryption hashing or chunking so users can view or modify data

stored in hidden fields

Cookies Web applications can store small pieces of data in the clientrsquos Web browserby using cookies A cookie is a small amount of data that is stored either in a text file

on the client file system (if the cookie is persistent) or in memory in the clientbrowser session (if the cookie is temporary) The most common use of cookies is to

identify a single user as he or she visits multiple Web pages

Reading and Writing Cookies

A Web application creates a cookie by sending it to the client as a header in an HTTP

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1653

response The Web browser then submits the same cookie to the server with everynew request

Create a cookie -gt add a value to the ResponseCookies HttpCookieCollectionRead a cookie -gt read values in RequestCookies

Example

Check if cookie exists and display it if it does

if (RequestCookies[lastVisit] = null) Encode the cookie in case thecookie contains client-side script Label1Text =ServerHtmlEncode(RequestCookies[lastVisit]Value)

else Label1Text = No value defined

Define the cookie for the next visit ResponseCookies[lastVisit]Value =DateTimeNowToString()ResponseCookies[lastVisit]Expires =DateTimeNowAddDays(1)

If you do not define the Expires property the browser stores it in memory and the

cookie is lost if the user closes his or her browser

To delete a cookie overwrite the cookie and set an expiration date in the past Youcanrsquot directly delete cookies because they are stored on the clientrsquos computer

Controlling the Cookie Scope By default browsers wonrsquot send a cookie to a Web sitewith a different hostname You can control a cookiersquos scope to either limit the scope

to a specific folder on the Web server or expand the scope to any server in a domainTo limit the scope of a cookie to a folder set the Path property as the following

example demonstrates

Example

ResponseCookies[lastVisit]Path = Application1

Through this the scope is limited to the ldquoApplication1rdquo folder that is the browser

submits the cookie to any page with in this folder and not to pages in other folderseven if the folder is in the same server We can expand the scope to a particular

domain using the following statementExample

ResponseCookies[ldquolastVisitrdquo]Domain = ldquoContosordquo

Storing Multiple Values in a CookieThough it depends on the browser you typically canrsquot store more than 20 cookies

per site and each cookie can be a maximum of 4 KB in length To work around the

20-cookie limit you can store multiple values in a cookie as the following codedemonstratesExample

ResponseCookies[info][visit]Value = DateTimeNowToString()

ResponseCookies[info][firstName]Value = Tony

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1253

PreInit

You can use this event to

Create recreate dynamic controls

Set a master page or theme dynamically

Access profile properties

Init

Used to read or initialize your control properties

InitComplete

Used when you need to access your properties after they have been initialized

PreLoad

Used when you need to process things before the Load event has been fired

Load

The Pagersquos OnLoad method and all of its child controlrsquos OnLoad method are firedrecursively This event is used to set properties and make database connections

Control Events

Control specific events are handled at this stage eg Click eventrsquos for the button control

LoadComplete

This stage is for when you need to access controls that have been properly loaded

PreRender

Can be used to make any lsquolast chancersquo changes to the controls before they are rendered

SaveStateComplete

This event is used for things that require view state to be saved yet not making anychanges to the controls themselves

Render

The page object calls this method on all of the controls so all the controls are written andsent to the browser

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1353

Unload

All the controls UnLoad method are fired followed by the pages UnLoad event (bottom-

up) This stage is used for closing database connections closing open files etc

It is import to understand that each server control has its very own life cycle but they arefired recursively so things may not occur at the time you think they do (they occur in

reverse order) What this means is that some events fire from the bottom up like the Init

event while others load from the top-down like the Load event

Purpose

State management is the process by which you maintain state and page information

over multiple requests for the same or different pages

Types of State Management

There are 2 types State Management

1 Client ndash Side State Management This stores information on the clients computer by embedding the information into a

Web page a uniform resource locator(url) or a cookie The techniques available tostore the state information at the client end are listed down below

a View State ndash AspNet uses View State to track the values in the Controls You can

add custom values to the view state It is used by the Aspnet page framework toautomatically save the values of the page and of each control just prior to rendering

to the page When the page is posted one of the first tasks performed by page

processing is to restore view state

b Control State ndash If you create a custom control that requires view state to work

properly you should use control state to ensure other developers donrsquot break yourcontrol by disabling view state

c Hidden fields ndash Like view state hidden fields store data in an HTML form without

displaying it in the users browser The data is available only when the form isprocessed

d Cookies ndash Cookies store a value in the users browser that the browser sends with

every page request to the same server Cookies are the best way to store state datathat must be available for multiple Web pages on a web site

e Query Strings - Query strings store values in the URL that are visible to the userUse query strings when you want a user to be able to e-mail or instant message

state data with a URL

2 Server ndash Side State Management

a Application State - Application State information is available to all pagesregardless of which user requests a page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1453

b Session State ndash Session State information is available to all pages opened by auser during a single visit

Both application state and session state information is lost when the application

restarts To persist user data between application restarts you can store it usingprofile properties

Implementation Procedure

Client ndash Side State Management

View State

The ViewState property provides a dictionary object for retaining values betweenmultiple requests for the same page When an ASPNET page is processed the

current state of the page and controls is hashed into a string and saved in the pageas a hidden field If the data is too long for a single field then ASPNET performs

view state chunking (new in ASPNET 20) to split it across multiple hidden fields

The following code sample demonstrates how view state adds data as a hidden formwithin a Web pagersquos HTML

ltinput type=hidden name=__VIEWSTATE id=__VIEWSTATErdquovalue=wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHnrt75XFpMGnqjqHlH66cdw== gt

Encrypting of the View State You can enable view state encryption to make it more

difficult for attackers and malicious users to directly read view state informationThough this adds processing overhead to the Web server it supports in storing

confidential information in view state To configure view state encryption for an

application does the following

ltConfigurationgt

ltsystemwebgt

ltpages viewStateEncryptionMode=Alwaysgt

ltsystemwebgt

ltconfigurationgt

Alternatively you can enable view state encryption for a specific page by setting thevalue in the page directive as the following sample demonstrates

lt Page Language=C AutoEventWireup=true CodeFile=DefaultaspxcsInherits=_Default ViewStateEncryptionMode=Alwaysgt

View State is enabled by default but if you can disable it by setting the

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1553

EnableViewState property for each web control to false This reduces the serverprocessing time and decreases page size

Reading and Writing Custom View State DataIf you have a value that yoursquod like to keep track of while the user is visiting a single

ASPNET Web page adding a custom value to ViewState is the most efficient andsecure way to do that However ViewState is lost if the user visits a different Web

page so it is useful only for temporarily storing valuesExample Determine the time of last visit to the page

Check if View State object exists and display it if it does

If (ViewState [lastVisit]= null)

Label1Text = (string)ViewState[lastVisit] else

Label1Text = lastVisit ViewState not defined

Define the ViewState object for the next page viewViewStateAdd(lastVisit DateTimeNowToString())

Control State If you create a custom control that requires ViewState you can use

the ControlState property to store state information for your control ControlStateallows you to persist property information that is specific to a control and cannot be

turned off like the ViewState property To use control state in a custom control your

control must override the OnInit method and call the Register-RequiresControlStatemethod during initialization and then override the SaveControl-State and

LoadControlState methods

Hidden fields ViewState stores information in the Web page using hidden fieldsHidden fields are sent back to the server when the user submits a form however

the information is never displayed by the Web browser (unless the user chooses toview the page source) ASPNET allows you to create your own custom hidden fields

and store values that are submitted with other form data A HiddenField controlstores a single variable in its Value property and must be explicitly added to the

page You can use hidden fields only to store information for a single page so it isnot useful for storing session data If you use hidden fields you must submit your

pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which

happens if the user clicks a link) Unlike view state data hidden fields have no built-in compression encryption hashing or chunking so users can view or modify data

stored in hidden fields

Cookies Web applications can store small pieces of data in the clientrsquos Web browserby using cookies A cookie is a small amount of data that is stored either in a text file

on the client file system (if the cookie is persistent) or in memory in the clientbrowser session (if the cookie is temporary) The most common use of cookies is to

identify a single user as he or she visits multiple Web pages

Reading and Writing Cookies

A Web application creates a cookie by sending it to the client as a header in an HTTP

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1653

response The Web browser then submits the same cookie to the server with everynew request

Create a cookie -gt add a value to the ResponseCookies HttpCookieCollectionRead a cookie -gt read values in RequestCookies

Example

Check if cookie exists and display it if it does

if (RequestCookies[lastVisit] = null) Encode the cookie in case thecookie contains client-side script Label1Text =ServerHtmlEncode(RequestCookies[lastVisit]Value)

else Label1Text = No value defined

Define the cookie for the next visit ResponseCookies[lastVisit]Value =DateTimeNowToString()ResponseCookies[lastVisit]Expires =DateTimeNowAddDays(1)

If you do not define the Expires property the browser stores it in memory and the

cookie is lost if the user closes his or her browser

To delete a cookie overwrite the cookie and set an expiration date in the past Youcanrsquot directly delete cookies because they are stored on the clientrsquos computer

Controlling the Cookie Scope By default browsers wonrsquot send a cookie to a Web sitewith a different hostname You can control a cookiersquos scope to either limit the scope

to a specific folder on the Web server or expand the scope to any server in a domainTo limit the scope of a cookie to a folder set the Path property as the following

example demonstrates

Example

ResponseCookies[lastVisit]Path = Application1

Through this the scope is limited to the ldquoApplication1rdquo folder that is the browser

submits the cookie to any page with in this folder and not to pages in other folderseven if the folder is in the same server We can expand the scope to a particular

domain using the following statementExample

ResponseCookies[ldquolastVisitrdquo]Domain = ldquoContosordquo

Storing Multiple Values in a CookieThough it depends on the browser you typically canrsquot store more than 20 cookies

per site and each cookie can be a maximum of 4 KB in length To work around the

20-cookie limit you can store multiple values in a cookie as the following codedemonstratesExample

ResponseCookies[info][visit]Value = DateTimeNowToString()

ResponseCookies[info][firstName]Value = Tony

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1353

Unload

All the controls UnLoad method are fired followed by the pages UnLoad event (bottom-

up) This stage is used for closing database connections closing open files etc

It is import to understand that each server control has its very own life cycle but they arefired recursively so things may not occur at the time you think they do (they occur in

reverse order) What this means is that some events fire from the bottom up like the Init

event while others load from the top-down like the Load event

Purpose

State management is the process by which you maintain state and page information

over multiple requests for the same or different pages

Types of State Management

There are 2 types State Management

1 Client ndash Side State Management This stores information on the clients computer by embedding the information into a

Web page a uniform resource locator(url) or a cookie The techniques available tostore the state information at the client end are listed down below

a View State ndash AspNet uses View State to track the values in the Controls You can

add custom values to the view state It is used by the Aspnet page framework toautomatically save the values of the page and of each control just prior to rendering

to the page When the page is posted one of the first tasks performed by page

processing is to restore view state

b Control State ndash If you create a custom control that requires view state to work

properly you should use control state to ensure other developers donrsquot break yourcontrol by disabling view state

c Hidden fields ndash Like view state hidden fields store data in an HTML form without

displaying it in the users browser The data is available only when the form isprocessed

d Cookies ndash Cookies store a value in the users browser that the browser sends with

every page request to the same server Cookies are the best way to store state datathat must be available for multiple Web pages on a web site

e Query Strings - Query strings store values in the URL that are visible to the userUse query strings when you want a user to be able to e-mail or instant message

state data with a URL

2 Server ndash Side State Management

a Application State - Application State information is available to all pagesregardless of which user requests a page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1453

b Session State ndash Session State information is available to all pages opened by auser during a single visit

Both application state and session state information is lost when the application

restarts To persist user data between application restarts you can store it usingprofile properties

Implementation Procedure

Client ndash Side State Management

View State

The ViewState property provides a dictionary object for retaining values betweenmultiple requests for the same page When an ASPNET page is processed the

current state of the page and controls is hashed into a string and saved in the pageas a hidden field If the data is too long for a single field then ASPNET performs

view state chunking (new in ASPNET 20) to split it across multiple hidden fields

The following code sample demonstrates how view state adds data as a hidden formwithin a Web pagersquos HTML

ltinput type=hidden name=__VIEWSTATE id=__VIEWSTATErdquovalue=wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHnrt75XFpMGnqjqHlH66cdw== gt

Encrypting of the View State You can enable view state encryption to make it more

difficult for attackers and malicious users to directly read view state informationThough this adds processing overhead to the Web server it supports in storing

confidential information in view state To configure view state encryption for an

application does the following

ltConfigurationgt

ltsystemwebgt

ltpages viewStateEncryptionMode=Alwaysgt

ltsystemwebgt

ltconfigurationgt

Alternatively you can enable view state encryption for a specific page by setting thevalue in the page directive as the following sample demonstrates

lt Page Language=C AutoEventWireup=true CodeFile=DefaultaspxcsInherits=_Default ViewStateEncryptionMode=Alwaysgt

View State is enabled by default but if you can disable it by setting the

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1553

EnableViewState property for each web control to false This reduces the serverprocessing time and decreases page size

Reading and Writing Custom View State DataIf you have a value that yoursquod like to keep track of while the user is visiting a single

ASPNET Web page adding a custom value to ViewState is the most efficient andsecure way to do that However ViewState is lost if the user visits a different Web

page so it is useful only for temporarily storing valuesExample Determine the time of last visit to the page

Check if View State object exists and display it if it does

If (ViewState [lastVisit]= null)

Label1Text = (string)ViewState[lastVisit] else

Label1Text = lastVisit ViewState not defined

Define the ViewState object for the next page viewViewStateAdd(lastVisit DateTimeNowToString())

Control State If you create a custom control that requires ViewState you can use

the ControlState property to store state information for your control ControlStateallows you to persist property information that is specific to a control and cannot be

turned off like the ViewState property To use control state in a custom control your

control must override the OnInit method and call the Register-RequiresControlStatemethod during initialization and then override the SaveControl-State and

LoadControlState methods

Hidden fields ViewState stores information in the Web page using hidden fieldsHidden fields are sent back to the server when the user submits a form however

the information is never displayed by the Web browser (unless the user chooses toview the page source) ASPNET allows you to create your own custom hidden fields

and store values that are submitted with other form data A HiddenField controlstores a single variable in its Value property and must be explicitly added to the

page You can use hidden fields only to store information for a single page so it isnot useful for storing session data If you use hidden fields you must submit your

pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which

happens if the user clicks a link) Unlike view state data hidden fields have no built-in compression encryption hashing or chunking so users can view or modify data

stored in hidden fields

Cookies Web applications can store small pieces of data in the clientrsquos Web browserby using cookies A cookie is a small amount of data that is stored either in a text file

on the client file system (if the cookie is persistent) or in memory in the clientbrowser session (if the cookie is temporary) The most common use of cookies is to

identify a single user as he or she visits multiple Web pages

Reading and Writing Cookies

A Web application creates a cookie by sending it to the client as a header in an HTTP

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1653

response The Web browser then submits the same cookie to the server with everynew request

Create a cookie -gt add a value to the ResponseCookies HttpCookieCollectionRead a cookie -gt read values in RequestCookies

Example

Check if cookie exists and display it if it does

if (RequestCookies[lastVisit] = null) Encode the cookie in case thecookie contains client-side script Label1Text =ServerHtmlEncode(RequestCookies[lastVisit]Value)

else Label1Text = No value defined

Define the cookie for the next visit ResponseCookies[lastVisit]Value =DateTimeNowToString()ResponseCookies[lastVisit]Expires =DateTimeNowAddDays(1)

If you do not define the Expires property the browser stores it in memory and the

cookie is lost if the user closes his or her browser

To delete a cookie overwrite the cookie and set an expiration date in the past Youcanrsquot directly delete cookies because they are stored on the clientrsquos computer

Controlling the Cookie Scope By default browsers wonrsquot send a cookie to a Web sitewith a different hostname You can control a cookiersquos scope to either limit the scope

to a specific folder on the Web server or expand the scope to any server in a domainTo limit the scope of a cookie to a folder set the Path property as the following

example demonstrates

Example

ResponseCookies[lastVisit]Path = Application1

Through this the scope is limited to the ldquoApplication1rdquo folder that is the browser

submits the cookie to any page with in this folder and not to pages in other folderseven if the folder is in the same server We can expand the scope to a particular

domain using the following statementExample

ResponseCookies[ldquolastVisitrdquo]Domain = ldquoContosordquo

Storing Multiple Values in a CookieThough it depends on the browser you typically canrsquot store more than 20 cookies

per site and each cookie can be a maximum of 4 KB in length To work around the

20-cookie limit you can store multiple values in a cookie as the following codedemonstratesExample

ResponseCookies[info][visit]Value = DateTimeNowToString()

ResponseCookies[info][firstName]Value = Tony

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1453

b Session State ndash Session State information is available to all pages opened by auser during a single visit

Both application state and session state information is lost when the application

restarts To persist user data between application restarts you can store it usingprofile properties

Implementation Procedure

Client ndash Side State Management

View State

The ViewState property provides a dictionary object for retaining values betweenmultiple requests for the same page When an ASPNET page is processed the

current state of the page and controls is hashed into a string and saved in the pageas a hidden field If the data is too long for a single field then ASPNET performs

view state chunking (new in ASPNET 20) to split it across multiple hidden fields

The following code sample demonstrates how view state adds data as a hidden formwithin a Web pagersquos HTML

ltinput type=hidden name=__VIEWSTATE id=__VIEWSTATErdquovalue=wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHnrt75XFpMGnqjqHlH66cdw== gt

Encrypting of the View State You can enable view state encryption to make it more

difficult for attackers and malicious users to directly read view state informationThough this adds processing overhead to the Web server it supports in storing

confidential information in view state To configure view state encryption for an

application does the following

ltConfigurationgt

ltsystemwebgt

ltpages viewStateEncryptionMode=Alwaysgt

ltsystemwebgt

ltconfigurationgt

Alternatively you can enable view state encryption for a specific page by setting thevalue in the page directive as the following sample demonstrates

lt Page Language=C AutoEventWireup=true CodeFile=DefaultaspxcsInherits=_Default ViewStateEncryptionMode=Alwaysgt

View State is enabled by default but if you can disable it by setting the

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1553

EnableViewState property for each web control to false This reduces the serverprocessing time and decreases page size

Reading and Writing Custom View State DataIf you have a value that yoursquod like to keep track of while the user is visiting a single

ASPNET Web page adding a custom value to ViewState is the most efficient andsecure way to do that However ViewState is lost if the user visits a different Web

page so it is useful only for temporarily storing valuesExample Determine the time of last visit to the page

Check if View State object exists and display it if it does

If (ViewState [lastVisit]= null)

Label1Text = (string)ViewState[lastVisit] else

Label1Text = lastVisit ViewState not defined

Define the ViewState object for the next page viewViewStateAdd(lastVisit DateTimeNowToString())

Control State If you create a custom control that requires ViewState you can use

the ControlState property to store state information for your control ControlStateallows you to persist property information that is specific to a control and cannot be

turned off like the ViewState property To use control state in a custom control your

control must override the OnInit method and call the Register-RequiresControlStatemethod during initialization and then override the SaveControl-State and

LoadControlState methods

Hidden fields ViewState stores information in the Web page using hidden fieldsHidden fields are sent back to the server when the user submits a form however

the information is never displayed by the Web browser (unless the user chooses toview the page source) ASPNET allows you to create your own custom hidden fields

and store values that are submitted with other form data A HiddenField controlstores a single variable in its Value property and must be explicitly added to the

page You can use hidden fields only to store information for a single page so it isnot useful for storing session data If you use hidden fields you must submit your

pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which

happens if the user clicks a link) Unlike view state data hidden fields have no built-in compression encryption hashing or chunking so users can view or modify data

stored in hidden fields

Cookies Web applications can store small pieces of data in the clientrsquos Web browserby using cookies A cookie is a small amount of data that is stored either in a text file

on the client file system (if the cookie is persistent) or in memory in the clientbrowser session (if the cookie is temporary) The most common use of cookies is to

identify a single user as he or she visits multiple Web pages

Reading and Writing Cookies

A Web application creates a cookie by sending it to the client as a header in an HTTP

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1653

response The Web browser then submits the same cookie to the server with everynew request

Create a cookie -gt add a value to the ResponseCookies HttpCookieCollectionRead a cookie -gt read values in RequestCookies

Example

Check if cookie exists and display it if it does

if (RequestCookies[lastVisit] = null) Encode the cookie in case thecookie contains client-side script Label1Text =ServerHtmlEncode(RequestCookies[lastVisit]Value)

else Label1Text = No value defined

Define the cookie for the next visit ResponseCookies[lastVisit]Value =DateTimeNowToString()ResponseCookies[lastVisit]Expires =DateTimeNowAddDays(1)

If you do not define the Expires property the browser stores it in memory and the

cookie is lost if the user closes his or her browser

To delete a cookie overwrite the cookie and set an expiration date in the past Youcanrsquot directly delete cookies because they are stored on the clientrsquos computer

Controlling the Cookie Scope By default browsers wonrsquot send a cookie to a Web sitewith a different hostname You can control a cookiersquos scope to either limit the scope

to a specific folder on the Web server or expand the scope to any server in a domainTo limit the scope of a cookie to a folder set the Path property as the following

example demonstrates

Example

ResponseCookies[lastVisit]Path = Application1

Through this the scope is limited to the ldquoApplication1rdquo folder that is the browser

submits the cookie to any page with in this folder and not to pages in other folderseven if the folder is in the same server We can expand the scope to a particular

domain using the following statementExample

ResponseCookies[ldquolastVisitrdquo]Domain = ldquoContosordquo

Storing Multiple Values in a CookieThough it depends on the browser you typically canrsquot store more than 20 cookies

per site and each cookie can be a maximum of 4 KB in length To work around the

20-cookie limit you can store multiple values in a cookie as the following codedemonstratesExample

ResponseCookies[info][visit]Value = DateTimeNowToString()

ResponseCookies[info][firstName]Value = Tony

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1553

EnableViewState property for each web control to false This reduces the serverprocessing time and decreases page size

Reading and Writing Custom View State DataIf you have a value that yoursquod like to keep track of while the user is visiting a single

ASPNET Web page adding a custom value to ViewState is the most efficient andsecure way to do that However ViewState is lost if the user visits a different Web

page so it is useful only for temporarily storing valuesExample Determine the time of last visit to the page

Check if View State object exists and display it if it does

If (ViewState [lastVisit]= null)

Label1Text = (string)ViewState[lastVisit] else

Label1Text = lastVisit ViewState not defined

Define the ViewState object for the next page viewViewStateAdd(lastVisit DateTimeNowToString())

Control State If you create a custom control that requires ViewState you can use

the ControlState property to store state information for your control ControlStateallows you to persist property information that is specific to a control and cannot be

turned off like the ViewState property To use control state in a custom control your

control must override the OnInit method and call the Register-RequiresControlStatemethod during initialization and then override the SaveControl-State and

LoadControlState methods

Hidden fields ViewState stores information in the Web page using hidden fieldsHidden fields are sent back to the server when the user submits a form however

the information is never displayed by the Web browser (unless the user chooses toview the page source) ASPNET allows you to create your own custom hidden fields

and store values that are submitted with other form data A HiddenField controlstores a single variable in its Value property and must be explicitly added to the

page You can use hidden fields only to store information for a single page so it isnot useful for storing session data If you use hidden fields you must submit your

pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which

happens if the user clicks a link) Unlike view state data hidden fields have no built-in compression encryption hashing or chunking so users can view or modify data

stored in hidden fields

Cookies Web applications can store small pieces of data in the clientrsquos Web browserby using cookies A cookie is a small amount of data that is stored either in a text file

on the client file system (if the cookie is persistent) or in memory in the clientbrowser session (if the cookie is temporary) The most common use of cookies is to

identify a single user as he or she visits multiple Web pages

Reading and Writing Cookies

A Web application creates a cookie by sending it to the client as a header in an HTTP

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1653

response The Web browser then submits the same cookie to the server with everynew request

Create a cookie -gt add a value to the ResponseCookies HttpCookieCollectionRead a cookie -gt read values in RequestCookies

Example

Check if cookie exists and display it if it does

if (RequestCookies[lastVisit] = null) Encode the cookie in case thecookie contains client-side script Label1Text =ServerHtmlEncode(RequestCookies[lastVisit]Value)

else Label1Text = No value defined

Define the cookie for the next visit ResponseCookies[lastVisit]Value =DateTimeNowToString()ResponseCookies[lastVisit]Expires =DateTimeNowAddDays(1)

If you do not define the Expires property the browser stores it in memory and the

cookie is lost if the user closes his or her browser

To delete a cookie overwrite the cookie and set an expiration date in the past Youcanrsquot directly delete cookies because they are stored on the clientrsquos computer

Controlling the Cookie Scope By default browsers wonrsquot send a cookie to a Web sitewith a different hostname You can control a cookiersquos scope to either limit the scope

to a specific folder on the Web server or expand the scope to any server in a domainTo limit the scope of a cookie to a folder set the Path property as the following

example demonstrates

Example

ResponseCookies[lastVisit]Path = Application1

Through this the scope is limited to the ldquoApplication1rdquo folder that is the browser

submits the cookie to any page with in this folder and not to pages in other folderseven if the folder is in the same server We can expand the scope to a particular

domain using the following statementExample

ResponseCookies[ldquolastVisitrdquo]Domain = ldquoContosordquo

Storing Multiple Values in a CookieThough it depends on the browser you typically canrsquot store more than 20 cookies

per site and each cookie can be a maximum of 4 KB in length To work around the

20-cookie limit you can store multiple values in a cookie as the following codedemonstratesExample

ResponseCookies[info][visit]Value = DateTimeNowToString()

ResponseCookies[info][firstName]Value = Tony

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1653

response The Web browser then submits the same cookie to the server with everynew request

Create a cookie -gt add a value to the ResponseCookies HttpCookieCollectionRead a cookie -gt read values in RequestCookies

Example

Check if cookie exists and display it if it does

if (RequestCookies[lastVisit] = null) Encode the cookie in case thecookie contains client-side script Label1Text =ServerHtmlEncode(RequestCookies[lastVisit]Value)

else Label1Text = No value defined

Define the cookie for the next visit ResponseCookies[lastVisit]Value =DateTimeNowToString()ResponseCookies[lastVisit]Expires =DateTimeNowAddDays(1)

If you do not define the Expires property the browser stores it in memory and the

cookie is lost if the user closes his or her browser

To delete a cookie overwrite the cookie and set an expiration date in the past Youcanrsquot directly delete cookies because they are stored on the clientrsquos computer

Controlling the Cookie Scope By default browsers wonrsquot send a cookie to a Web sitewith a different hostname You can control a cookiersquos scope to either limit the scope

to a specific folder on the Web server or expand the scope to any server in a domainTo limit the scope of a cookie to a folder set the Path property as the following

example demonstrates

Example

ResponseCookies[lastVisit]Path = Application1

Through this the scope is limited to the ldquoApplication1rdquo folder that is the browser

submits the cookie to any page with in this folder and not to pages in other folderseven if the folder is in the same server We can expand the scope to a particular

domain using the following statementExample

ResponseCookies[ldquolastVisitrdquo]Domain = ldquoContosordquo

Storing Multiple Values in a CookieThough it depends on the browser you typically canrsquot store more than 20 cookies

per site and each cookie can be a maximum of 4 KB in length To work around the

20-cookie limit you can store multiple values in a cookie as the following codedemonstratesExample

ResponseCookies[info][visit]Value = DateTimeNowToString()

ResponseCookies[info][firstName]Value = Tony

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1753

ResponseCookies[info][border]Value = blue

ResponseCookies[info]Expires = DateTimeNowAddDays(1)

Running the code in this example sends a cookie with the following value to the Webbrowser

(visit=452006 23518 PM) (firstName=Tony) (border=blue)

Query Strings Query strings are commonly used to store variables that identify

specific pages such as search terms or page numbers A query string is informationthat is appended to the end of a page URL A typical query string might look like the

following real-world examplehttpsupportmicrosoftcomDefaultaspxkbid=315233

In this example the URL identifies the Defaultaspx page The query string (which

starts with a question mark []) contains a single parameter named ldquokbidrdquo and avalue for that parameter ldquo315233rdquo Query strings can also have multiple

parameters such as the following real-world URL which specifies a language andquery when searching the Microsoftcom Web site

httpsearchmicrosoftcomresultsaspxmkt=en-USampsetlang=en-USampq=hello+world

Value Name | ASPNET Object | Value

mkt | RequestQueryString[ldquomktrdquo] | en-USsetlang | RequestQueryString[ldquosetlangrdquo] | en-US

q | RequestQueryString[ldquoqrdquo] | hello world

Limitations for Query Strings1 Some Browsers and client devices impose a 2083 ndash character limit on the length

of the URL2 You must submit the page using an HTTP GET command in order for query string

values to be available during page processing Therefore you shouldnrsquot add querystrings to button targets in forms

3 You must manually add query string values to every hyperlink that the user mightclick

Example

Label1Text = User + ServerHtmlEncode(RequestQueryString[user]) +

Prefs + ServerHtmlEncode(RequestQueryString[prefs]) +

Page + ServerHtmlEncode(RequestQueryString[page])

Server - Side State Management

Application State ASPNET allows you to save values using application state a

global storage mechanism that is accessible from all pages in the Web applicationApplication state is stored in the Application keyvalue dictionary Once you add your

application-specific information to application state the server manages it and it isnever exposed to the client Application state is a great place to store information

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1853

that is not user-specific By storing it in the application state all pages can accessdata from a single location in memory rather than keeping separate copies of the

data Data stored in the Application object is not permanent and is lost any time theapplication is restarted

ASPNET provides three events that enable you to initialize Application variables (free

resources when the application shuts down) and respond to Application errors

a Application_Start Raised when the application starts This is the perfect place to

initialize Application variables

b Application_End Raised when an application shuts down Use this to free

application resources and perform logging

c Application_Error Raised when an unhandled error occurs Use this to performerror logging

Session State ASPNET allows you to save values using session state a storage

mechanism that is accessible from all pages requested by a single Web browsersession Therefore you can use session state to store user-specific informationSession state is similar to application state except that it is scoped to the current

browser session If different users are using your application each user session hasa different session state In addition if a user leaves your application and then

returns later after the session timeout period session state information is lost and anew session is created for the user Session state is stored in the Session keyvalue

dictionary

You can use session state to accomplish the following tasksi Uniquely identify browser or client-device requests and map them to individual

session instances on the server This allows you to track which pages a user saw on

your site during a specific visit

ii Store session-specific data on the server for use across multiple browser or client-device requests during the same session This is perfect for storing shopping cart

information

iii Raise appropriate session management events In addition you can write

application code leveraging these events

ASPNET session state supports several different storage options for session data

a InProc Stores session state in memory on the Web server This is the default andit offers much better performance than using the ASPNET state service or storing

state information in a database server InProc is fine for simple applications butrobust applications that use multiple Web servers or must persist session data

between application restarts should use State Server or SQLServer

b StateServer Stores session state in a service called the ASPNET State ServiceThis ensures that session state is preserved if the Web application is restarted and

also makes session state available to multiple Web servers in a Web farm ASPNETState Service is included with any computer set up to run ASPNET Web applications

however the service is set up to start manually by default Therefore when

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 1953

configuring the ASPNET State Service you must set the startup type to Automatic

c SQLServer Stores session state in a SQL Server database This ensures thatsession state is preserved if the Web application is restarted and also makes session

state available to multiple Web servers in a Web farm On the same hardware theASPNET State Service outperforms SQLServer However a SQL Server database

offers more robust data integrity and reporting capabilities

d Custom Enables you to specify a custom storage provider You also need to

implement the custom storage provider

e Off Disables session state You should disable session state if you are not using it

to improve performance

Advantages

Advantages of Client ndash Side State Management

1 Better Scalability With server-side state management each client that connectsto the Web server consumes memory on the Web server If a Web site has hundreds

or thousands of simultaneous users the memory consumed by storing state

management information can become a limiting factor Pushing this burden to theclients removes that potential bottleneck

2 Supports multiple Web servers With client-side state management you can

distribute incoming requests across multiple Web servers with no changes to your

application because the client provides all the information the Web server needs toprocess the request With server-side state management if a client switches servers

in the middle of the session the new server does not necessarily have access to theclientrsquos state information You can use multiple servers with server-side state

management but you need either intelligent load-balancing (to always forwardrequests from a client to the same server) or centralized state management (where

state is stored in a central database that all Web servers access)

Advantages of Server ndash Side State Management

1 Better security Client-side state management information can be captured (eitherin transit or while it is stored on the client) or maliciously modified Therefore you

should never use client-side state management to store confidential informationsuch as a password authorization level or authentication status

2 Reduced bandwidth If you store large amounts of state management information

sending that information back and forth to the client can increase bandwidthutilization and page load times potentially increasing your costs and reducing

scalability The increased bandwidth usage affects mobile clients most of all becausethey often have very slow connections Instead you should store large amounts of

state management data (say more than 1 KB) on the server

Caching in ASPNET

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2053

Category ASPNETComments (5)

This tutorial explains about The Importance of Caching Declarative Page Output

Caching Programmatic Page Caching Caching Page Fragments Caching Data and

Monitoring Performance

Introduction

Sponsored Links

Caching is one of the coolest features in Aspnet Caching enables you to store the expensivedata into Cache object and later retrieve it without doing expensive operations A verycommon example where you want to use caching is datagrid paging I am sure you all arefamiliar with datagrid paging which enables you to view the records in multiple pages Eachtime you visit a different page all the records are fetched from the database This becomes

very expensive operation Caching can save a lot of expensive operations since you can storeall the records in the cache object and use the cache object as the data source In this articlewe will see some important features that caching provides

Output Caching

Output caching is used for pages and is also known as Page-level caching All you need

to do to enable output caching is to add a directive in your html view of the aspx page

The output directive can be written like this

OutputCache Duration=60 VaryByParam=none

The page will be cached for 60 seconds the VaryByParam attribute is set to none which

means that there is no sort of caching implemented Hence if the first user requested page

which contains item1 than the second user will also see item1 even if he is requestingitem2

Thats why we always specify what the caching depends on

OutputCache Duration=60 VaryByParam=Category

In the above OutputCache directive you can notice that I changed the VaryByParam

attribute to Category which means that now the result of caching depends uponCategory Here Category represents the name of the column in the database

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2153

Programmatic Page Caching

You can also use caching programmatically meaning that you can change the value of cache depending upon the tasks performed by the user The ResponseCache class lets

you access the functionality to work with the cache object

You can change the expiration time on the Cache using the SetExpires method of the

ResponseCache class

ResponseCacheSetExpires(SystemDateTimeNowAddMinutes(10))

In the same way you can also use ResponseCacheVaryByParams to set the Params

programmatically

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library You cannot use

Response class anymore since its only limited to the aspnet code behind page For

accessing cache in class library you will have to use HttpContextCurrentCache Also

dont forget to include Systemweb namespace

Data Caching

Caching is one of the coolest features in Aspnet Caching enables you to store theexpensive data into Cache object and later retrieve it without doing expensive operations

Data Caching can tremendously increase performance since each time the data is

requested you can turn to the Cache object rather than going to the database and fetchingthe result

Sponsored Links

You all must be familiar with datagrid paging where you can display certain number of recordsin the datagrid control and use the numeric or next-previous buttons to view the otherrecords All the records are fetched for each and every page in the datagrid Meaning that if you have 40000 records in the database and you are using paging Each time you click to goto the next page you retrieve 40000 records This is way too much performance kill Thats

why for this task we can use Data Caching lets see how we can use data caching to make ourapplication more efficient

private void Button3_Click(object sender SystemEventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2253

if(Cache[MyArticles] == null)

Go to the database and fetch the result in the DataSet

Assign the dataset to the Cache object

Cache[MyArticles] = ds

else

This means that Cache is not empty and there is data in the cache

Extract the value of Cache object to the DataSet

DataSet ds = (DataSet) Cache[MyArticles]

The above example is pretty much simple and as you have also noticed that the syntax for

using Data Caching is very similar to the ViewState object By using this technique youwill only get the data from the database if the Cache is empty And if you see the page

source you will not find any hidden fields since Cache is stored in memory rather than in

page source

Caching Page Fragments

Fragment Caching refers to caching the sections of the page These sections are mostcommonly UserControls Page fragment caching allows you to cache the small portion of

the page instead of caching the whole page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2453

one of the most accessed pages The functionality of adding updating or deleting isusually less intensive compared to more transaction-based systems like Purchase

ordering Voucher creation etc Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources hence is

lot better to cache or persist the data to avoid this costly loss of resources

The NET Advantage

ASPNET provides the flexibility in terms of caching at different levels

1 Page Level Output Caching

This is at the page level and one of the easiest means for caching pages This

requires one to specify Duration of cache and Attribute of caching

Syntax lt OutputCache Duration=60 VaryByParam=none gt

The above syntax specifies that the page be cached for duration of 60 seconds and

the value none for VaryByParam attribute makes sure that there is a singlecached page available for this duration specified

VaryByParam can take various key parameter names in query string Also there

are other attributes like VaryByHeader VaryByCustom etc Please refer to MSDN for

more on this

2 Fragment Caching

Even though this definition refers to caching portions of page it is actually caching auser control that can be used in a base web form page In theory if you have used

include files in the traditional ASP model then this caching model is like caching theseinclude files separately In ASPNET more often this is done through User Controls

Initially even though one feels a bit misleading this is a significant technique thatcan be used especially when implementing n instances of the controls in various

aspx pages We can use the same syntax that we declared for the page levelcaching as shown above but the power of fragment caching comes from the

attribute VaryByControl Using this attribute one can cache a user control based onthe properties exposed

Syntax lt OutputCache Duration=60 VaryByControl=DepartmentId gt

The above syntax when declared within an ascx file ensures that the control is

cached for 60 seconds and the number of representations of cached control isdependant on the property DepartmentId declared in the control

Add the following into an ascx file Please note the use of tag Control and the

cache declaration

lt Control Language=Cgt

lt outputcache duration=60 varybycontrol=DepartMentId gt

ltscript runat=servergtprivate int _Departmentid=0

public int DepartMentId

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2553

getreturn _Departmentidset_Departmentid =value

Load event of control

void Page_Load(Object sender EventArgs e)

lblTextText = Time is + DateTimeNowToString() + for Department id = + _Departmentid + n

ltscriptgt

ltaspLabel id=lblText runat=servergtltaspLabelgt

Add the following to an aspx file Please note the way Register tag is used thedeclaration of control using syntax lt[TagPrefix][TagName]gt Usage of property

DepartMentId Open the page in two browsers and closely watch the Base formtiming and the User control timing Also note that the following page results in two

copies or representation of user control in the cache

lt Page Language=C Trace=true gt

lt Register TagPrefix=CacheSample TagName=TextSrc=CachingControlascx gtltscript runat=servergt

void Page_Load(Object sender EventArgs e)

thislbltimeText =Base form time is + DateTimeNowToString() + n

ltscriptgtlthtmlgt

ltheadgtltheadgt

ltbodygt

ltform runat=server ID=Form2gtlttablegt

lttbodygtlttrgt

lttdgtltaspLabel id=lbltime runat=servergtltaspLabelgt

lttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance1 runat=Server DepartMentId=0gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttrgt

lttdgtltCACHESAMPLETEXT id=instance2 runat=Server DepartMentId=1gt

ltCACHESAMPLETEXTgtlttdgt

lttrgtlttbodygt

lttablegt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2653

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2753

required instead of caching the data at the page level

CacheInsert(UsersdsUsersnewSystemWebCachingCacheDependency(ServerMapPath(Masterxml))

DateTimeNowAddSeconds(45)TimeSpanZero)

For other overloaded parameters refer MSDN

Also note how we could use trace within to add my own statements

HttpContextCurrentTraceWrite(from Database)

lt Page Language=c Trace=true gtlt import Namespace=System gt

lt import Namespace=SystemData gtlt import Namespace=SystemDataSqlClient gt

lt import Namespace=SystemConfiguration gtlt import Namespace=SystemWeb gt

lt import Namespace=SystemCollections gt

lt import Namespace=SystemIO gtltscript runat=servergtvoid Page_Load(Object sender EventArgs e)

DataSet dsUsers

try

if (Cache[Users]==null)

SqlConnection cndsUsers = new DataSet(new)

cn = new SqlConnection(ConfigurationSettingsAppSettingsGet(conn))

SqlDataAdapter daUsersdaUsers = new SqlDataAdapter(Select from tblUserscn)

cnOpen()daUsersFill(dsUserstblUsers)

Update the cache objectCacheInsert(UsersdsUsers new SystemWebCachingCacheDependency(

ServerMapPath(Masterxml)) DateTimeNowAddSeconds(45)TimeSpanZero)

HttpContextCurrentTraceWrite(DateTimeNowAddSeconds(45)ToString() + is expiry time)

cnClose()cnDispose()

HttpContextCurrentTraceWrite(from Database)lblChangeText =From the database

else

HttpContextCurrentTraceWrite(From cache)

lblChangeText =From the cachedsUsers= (DataSet) Cache[Users]

dlUsersDataSource =dsUsers

dlUsersDataMember = dsUsersTables[0]TableName

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2853

lblChangeText += ServerMapPath(Masterxml)thisDataBind()

catch(Exception ex)

lblChangeText = exMessage

ltscriptgt

ltDOCTYPE HTML PUBLIC -W3CDTD HTML 40 TransitionalEN gt

lthtmlgtltheadgt

lttitlegtCache Dependency Testerlttitlegt ltmeta content=Microsoft Visual Studio 70 name=GENERATOR gt

ltmeta content=C name=CODE_LANGUAGE gtltmeta content=JavaScript name=vs_defaultClientScript gt

ltmeta content=httpschemasmicrosoftcomintellisenseie5name=vs_targetSchema gt

ltheadgt

ltbody ms_positioning=GridLayoutgtltform id=Form1 method=post runat=servergtltaspDataList id=dlUsers style=Z-INDEX 101 LEFT 44px POSITION absolute

TOP 104px runat=server Height=148px Width=343px BorderWidth=1pxGridLines=Horizontal CellPadding=4 BackColor=White ForeColor=Black

BorderStyle=None BorderColor=CCCCCCgtltSelectedItemStyle font-bold=True forecolor=White

backcolor=CC3333gtltSelectedItemStylegtltFooterStyle forecolor=Black backcolor=CCCC99gtltFooterStylegt

ltHeaderStyle font-bold=True forecolor=Whitebackcolor=333333gtltHeaderStylegt

ltItemTemplategt

lttablegtlttrgt

lttdgtltDataBinderEval(ContainerDataItemUserId)gtlttdgt

lttdgtltDataBinderEval(ContainerDataItemFirstName)gtlttdgt

lttdgt

ltDataBinderEval(ContainerDataItemLastName)gtlttdgtlttrgt

lttablegtltItemTemplategt

ltaspDataListgtltaspLabel id=lblChange style=Z-INDEX 102 LEFT 46px POSITION absolute

TOP 63px runat=server Height=28px Width=295pxgtltaspLabelgtltaspButton id=btnMaster style=Z-INDEX 103 LEFT 50px POSITION

absolute TOP 293px onclick=btnMaster_Click runat=server Text=RefreshMastergtltaspButtongt

ltformgtltbodygt

lthtmlgt

We created the page that initiates and uses the Cache For testing purpose we need

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 2953

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3053

lttrgtlttdgt

ltlabel id=lblRefresh runat=servergtRewrite the XML File by clicking the buttonbelowltlabelgt

lttdgtlttrgt

lttr align=middlegtlttdgtltaspButton id=btnMaster onclick=btnMaster_Click runat=server

Text=Write XMLgtltaspButtongt

lttdgtlttrgt

lttbodygtlttablegt

ltspangtltformgt

ltbodygtlthtmlgt

Now once you have created the above pages ie one that implements caching andother that overwrites the dependency file create two instance of browser and openthe cache implementation page and note for trace label text open the other

instance of browser with the page which overwrites the XML Note the former thefirst time it fetches data from the database and the subsequent request will be from

cache till your expiration time of 45 seconds is reached or anyone overwrites orchanges the Masterxml file Also give a look on Timespan parameter since you

have a concept of Sliding expiration that can also be implemented Keep refreshingthe first page and you will see that trace indicates the cached page retrieval Click

the overwrite XML button on the latter page that would overwrite the XML and againrefresh the former page to note that the data is retrieved from database Though in

this example I have not shown any direct relation between the cached data and the

dependency file (like get values from dependency file and merge with cached objectetc) in terms of integrated usage this could very easily be designed and

implemented Dependency caching is a powerful technique that NET supports andshould be utilized wherever applicable

Conclusion

Caching is a technique that definitely improves the performance of web applications

if one is careful to have a balance in terms of which data needs to be cached andparameter values for expiration policy

User Control can access only within the current applicationif u want to access the

user control to other applicationu want to copy that user control to that application

Custom control can access from any application becs it is stored in GAC(Global

Assembly Cache)

We can add the custom control to Visual studio IDE toolboxbut user control cant

User control is good for static layoutCustom control is good for dynamic layout

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3153

User Control will appear in the Solution Explorer where as custom control will appearin the toolbox

the significant of both controls is re-usabilityUser control will use with in theapplication where as custom control will use in any application because it is in the

tool boxExtending the functionality of the existing control is Custom Control and grouping up

of existing controls for desired out put is user control

Difference between user controls and custom controls in net (vb c net with aspnet)User controls

It is newly concept in net it same like as inheritance concept in oopsIn aspnet the base class is systemwebuipage objectWhen ever creating user control that will be converting as a class and this class becomeSubclasses of Systemwebuipage class at compile timeUser control extension with ascxLet us see program how build (at end I will mention difference between user control and

Custom control)

Let us consider with help of IDE

lt Control Language =rdquovbrdquogtltformgtltAsp Label id=rdquol1rdquo text ldquoenter yr namerdquo runat =rdquoserverrdquogtltAsp Textbox id=rdquot1rdquo runat=rdquoserverrdquogtltformgt

Now this save as labeltextboxascx (user control)Now this user control can be used for any page in your web applicationThis can be done byAs fallow (just u write in code behind page)

lt Register tagprefix=rdquoraghurdquo tagname=rdquochinnirdquo src=rdquo labeltextboxascxrdquogt

Now create instance for user control in html file of aspx page

ltRaghu chinni id=rdquoltrdquo runat =rdquoserverrdquogt

Custom controlCreating user controls which are essentially reusable small web pagesYou can also create your own compiled custom controlsThere are three ways to create custom controls1) Create a derived custom control by deriving from an existing control2) Create a composite control by grouping existing controls together into a new compiledcontrol3) Create a full custom control by deriving from SystemWebUIWebControlsWebControl

Composite controls are most similar to user controls The key difference is that compositeControls are compiled into a DLL and used as you would any server controlLet us programmatically that will help how to build

Iam explaining on simple example

Take notepad example

Imports SystemComponentModelImports SystemWebUI

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3253

(lt0 WebCustomControl1 runat=servergt)gtPublic Class WebCustomControl1Inherits SystemWebUIWebControlsWebControl

Dim text As String

Property [Text]() As StringGetReturn textEnd Get

Set(ByVal Value As String)text = Value

End SetEnd Property

Protected Overrides Sub Render(ByVal output As SystemWebUIHtmlTextWriter)outputWrite([Text])

End Sub

End Class

Now compile then it generate one dll

Now open IDE language is vbnet with aspnetJust write in html of vb page

lt Register Tag prefix=rdquoraghurdquo namespace=rdquochinnirdquo assembly= ldquoWebControlLibrary1rdquo gt

Now create instanceUnder

ltformgtltraghuchinni ID=rdquotatcisrdquo Text=rdquothis is placid manrdquogtltformgt

Now press F5

U gets output asthis is placid man

Let us see differencesUser control1) Reusability web page2) We canrsquot add to toolbox3) Just drag and drop from solution explorer to page (aspx)

4) U can register user control to Aspx page by Register tag5) A separate copy of the control is required in each application6) Good for static layout

7) Easier to create8)Not complied into DLL9) Here page (user page) can be converted as control thenWe can use as control in aspxCustom controls1) Reusability of control (or extend functionalities of existing control)2) We can add toolbox

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3453

For a Web site project if you make changes to the page that would affect the generatedclasswhether by adding controls or modifying your codethe compiled class code isinvalidated and a new class is generated For more information on compilation in Web siteprojects and in Web application projects see ASPNET Compilation Overview and WebApplication Projects versus Web Site Projects

The following illustration shows the inheritance model for the page class in a single-fileASPNET Web page

Code-Behind Pages

Code-behind pages are the default in Web application projects and are optional in Web

site projects In the code-behind model the pages markup and server-side elementsincluding control declarations are in an aspx file while your page code is in a separatecode file The code file contains a partial classthat is a class declaration with thekeyword partial (Partial in Visual Basic) indicating that it contains only some of the totalcode that makes up the full class for the page In the partial class you add the code thatyour application requires for the page This typically consists of event handlers but caninclude any methods or properties that you need

The inheritance model for code-behind pages is slightly more complex than that forsingle-file pages The model is this

1 The code-behind file contains a partial class that inherits from a base page classThe base page class can be the Page class or it can be another class that derives

from Page2 The aspx file contains an Inherits attribute in the Page directive that points tothe code-behind partial class

3 When the page is compiled ASPNET generates a partial class based on the aspxfile this class is a partial class of the code-behind class file The generated partialclass file contains declarations for the pages controls This partial class enablesyour code-behind file to be used as part of a complete class without requiring youto declare the controls explicitly

4 Finally ASPNET generates another class that inherits from the class generated inStep 3 This second generated class contains the code required to build the page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3553

The second generated class and the code-behind class are compiled into anassembly that runs to render output to the browser

The following illustration shows the inheritance model for the page class in a code-behindASPNET Web page

When you work with master pages and content pages both can use the same events

(such as Page_Load)Be sure you know which events come before others You arebringing two classes together to create a singlepage class and a specific order is

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3653

required When an end user requests a content page in the browser the eventordering is as follows

Master page child controls initialization All server controls contained within the

master page are first initializedContent page child controls initialization All server controls contained in the

content page are initializedMaster page initialization The master page itself is initializedContent page initialization The content page is initialized

Content page load The content page is loaded (this is the Page_Load event

followed by the Page_LoadComplete event)Master page load The master page is loaded (this is also the Page_Load event)

Master page child controls load The server controls on the master page areloaded onto the page

Content page child controls load The server controls on the content page areloaded onto the page

How to access master page controls from content pages

Consider the following scenario

Master Page

lt master language=C gt

lthtmlgtlthead id=Head1 runat=servergt

lttitlegtMaster Pagelttitlegtltheadgt

ltbodygtltform id=Form1 runat=servergt

lttable id=header style=WIDTH 100 HEIGHT80px cellspacing=1

cellpadding=1 border=1gtlttrgt

lttd width=100 style=TEXT-ALIGN centergtltasplabel runat=server id=Headergt

This is the default header in the MasterPageltasplabelgtlttdgt

lttrgt

lttablegt-------------------------------------------------------------------------------------

Content Page

lt page language=C master=~ExposeHeadermaster gt

ltscript runat=servergtvoid Page_Load(object sender SystemEventArgs e)

Label headerLabel = (Label)

MasterFindControl(Header) Header is my master page label idheaderLabelText = This label content is set through the Page_Load event of the

child page

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3753

ltscriptgt

Here I am using MasterFindControl with the master page controls id (The identifierfor the control to be found) Find control will search the current naming container for

a server control with the specified id parameter It returns the specified control ornull if the specified control does not exist

Calling JavaScript from ASPNET MasterPage and Content Pages - Part I

Calling JavaScript from Master and Content Pages confuses a lot of developers In

this article we will see some common problems and their solutions of callingJavaScript from a MasterContent page This article is Part I of the two part series

and will cover JavaScript in Master Pages The next article will cover JavaScript inContent pages

Update Part II of this article can be read over here Calling JavaScript from ASPNETMaster Page and Content Pages - Part II

Call JavaScript From Master PageYou can call an existing JavaScript function from a Master Page or can create one on

the fly Here are some common scenarios

1 Create a JavaScript function on the fly and call the JavaScript function inthe MasterPage Page_Load() event

C protected void Page_Load(object sender EventArgs e)

string someScript =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(thisGetType()onload someScript)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String =

someScript = ltscript language=javascriptgtalert(Called fromCodeBehind)ltscriptgt

PageClientScriptRegisterStartupScript(MeGetType() onloadsomeScript) End Sub

The PageClientScriptRegisterStartupScript() allows you to emit client-side script

blocks from code behind More info can be found over here

httpmsdnmicrosoftcomen-uslibrarysystemwebuiclientscriptmanagerregisterstartupscriptaspx2 Call an existing JavaScript function on MasterPage Page_Load() event

Let us assume you have an existing JavaScript function declared in between the

ltheadgt tags then herersquos how to call that function from Page_Load()lthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Master)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3853

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

C protected void Page_Load(object sender EventArgs e)

if (PageClientScriptIsStartupScriptRegistered(alert))

PageClientScriptRegisterStartupScript

(thisGetType() alert invokeMeMaster() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad If (Not PageClientScriptIsStartupScriptRegistered(alert))Then

PageClientScriptRegisterStartupScript(MeGetType()alert invokeMeMaster() True) End If End Sub

3 Call JavaScript function from MasterPage on Button click

If you want to call a JavaScript function on a Button click then herersquos how to do solthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function invokeMeMaster()

alert(I was invoked from Masterdotnetcurry)

ltscriptgt

ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

In the ltbodygt tag add a Button and use the OnClientClick to call this functionltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return invokeMeMaster()gt

The OnClientClick() is called before the postback occurs This gives us a place tocheck for some condition and cancel the submit if the condition is not satisfied We

will see an example in Tip 64 Access a control on the MasterPage using JavaScript

If you have a control on the MasterPage and need to access it using JavaScript then

herersquos how to do so In this sample we will test the length of the TextBox to see if

there are 5 or more letters If the number of letters is less than 5 the form submitwill be cancelled

Add a TextBox and a Button control in the MasterPage (outside theContentPlaceHolder) as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt ltaspPanel ID=panelMaster GroupingText=MasterPage controlsrunat=servergt

ltaspTextBox ID=txtMaster runat=servergtltaspTextBoxgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 3953

ltaspButton ID=btnMaster runat=server Text=ButtonOnClientClick=return accessMasterControl() gt ltbr gt ltaspPanelgt ltaspContentPlaceHolder id=ContentPlaceHolder1 runat=servergt

ltaspContentPlaceHoldergt ltdivgt ltformgtltbodygt

In the ltheadgt element of the MasterPage add the following codelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessMasterControl() if (documentgetElementById(lt=txtMasterClientIDgt)valuelength lt= 5)

alert(Minimum 5 characters required) return false

else return true

ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

5 Access a control on the Content Page from a MasterPage using JavaScriptIf you have a control on the Content Page which has to be accessed in the

MasterPage using JavaScript then herersquos how to do soOn the Content Page create a TextBox as shown below ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controls

runat=servergt ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspPanelgtltaspContentgt

Now access and populate the TextBox lsquotxtContentrsquo from the MasterPagelthead runat=servergt lttitlegtlttitlegt ltscript type=textjavascriptgt function accessControlContentPage()

var txtCont = documentgetElementById(lt=PageMasterFindControl(ContentPlaceHolder1)FindControl(txtContent)ClientID gt)

txtContvalue = I got populated using MasterPage ltscriptgt ltaspContentPlaceHolder id=head runat=servergt ltaspContentPlaceHoldergtltheadgt

6 Ask user before submitting the form on a MasterPage

In order to ask the user for a confirmation before submitting the form you can eitheruse code behind or can use simple mark up as shown below

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4053

Declare a Button control that causes postback and write the following code inMasterPagemastercs or vb

Cprotected void Page_Load(object sender EventArgs e) string myScript = ltscript type=textjavascriptgt

function askBeforeSubmit() var msg = Are you surereturn confirm(msg)ltscriptgtPageClientScriptRegisterClientScriptBlock(thisGetType()

MakeSure myScript)form1AttributesAdd(onsubmit return askBeforeSubmit())

VBNETProtected Sub Page_Load(ByVal sender As Object ByVal e As EventArgs) Dim myScript As String = ltscript type=textjavascriptgt ampControlCharsCrLf amp function askBeforeSubmit() ampControlCharsCrLf amp var msg = Are you sure amp

ControlCharsCrLf amp return confirm(msg) amp ControlCharsCrLf amp amp ControlCharsCrLf amp ltscriptgt

PageClientScriptRegisterClientScriptBlock(MeGetType()MakeSure myScript)

form1AttributesAdd(onsubmit return askBeforeSubmit())End Sub

If you want to avoid a code-behind approach you can ask the user for a confirmation

by using the OnClientClick() on the Submit buttonltaspButton ID=btnMaster runat=server Text=Button OnClientClick=return confirm(Are you sure)gt

Calling JavaScript from ASPNET Master

Page and Content Pages - Part II

In this article we will see some common problems and their solutions of calling

JavaScript from a MasterContent page This article is Part II of the series lsquoCallingJavaScript from ASPNET Master Page and Content Pagesrsquo and in this article we will

cover JavaScript in Content Pages Part I of this article can be read over here CallingJavaScript from ASPNET Master Page and Content Pages - Part I

Call JavaScript from Content PageHere are some common scenarios of executing JavaScript from a Content Page1 Create a JavaScript function on the fly and call the JavaScript function in

the Content Page Page_Load() eventC protected void Page_Load(object sender EventArgs e)

const string someScript = alertMe

if (ClientScriptIsStartupScriptRegistered(thisGetType()someScript))

ClientScriptRegisterStartupScript(thisGetType()

someScript alert(I was called from Content page)true)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4153

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsSystemEventArgs) Handles MeLoad Dim someScript As String = alertMe If (Not ClientScriptIsStartupScriptRegistered(MeGetType()someScript)) Then

ClientScriptRegisterStartupScript(MeGetType()someScript alert(I was called from Content page) True) End If End Sub

2 Call a JavaScript function declared in a js file from the Content Page

If you have a js file and want to call the function from your Content Page thenherersquos how to do so

Letrsquos create a js file called TestScriptjs and add the following function in the js filefunction insideJS()

alert(Inside js)

Assuming that your js file is kept in a Script folder reference the file in yourMasterPage in the following mannerlthead runat=servergt lttitlegtlttitlegt ltscript src=ScriptsTestScriptjs type=textjavascriptgtltscriptgt

Now in your Content Page(in our case Defaultaspxcs or vb) call the JavaScriptfunction on the Page_Load

C

protected void Page_Load(object sender EventArgs e)

if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then

MasterPageClientScriptRegisterStartupScript(MeGetType() alert insideJS() True) End If

End Sub3 Referencing the js file from a Content Page instead of the Master page

The approach shown above in Tip 2 works well however this approach would add areference to the js file for every page in the application (since we are adding the js

in the Master Page) If you want to avoid this approach then remove the referenceadded to the js file in Tip 2 in the Master Page Now add a reference to the js file

from the Content Page using the lsquoRegisterClientScriptIncludersquo as shown belowC protected void Page_Load(object sender EventArgs e)

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4253

PageClientScriptRegisterClientScriptInclude(selective

ResolveUrl(ScriptsTestScriptjs)) if (MasterPageClientScriptIsStartupScriptRegistered(alert))

MasterPageClientScriptRegisterStartupScript

(thisGetType() alert insideJS() true)

VBNET Protected Sub Page_Load(ByVal sender As Object ByVal e AsEventArgs)

PageClientScriptRegisterClientScriptInclude(selectiveResolveUrl(ScriptsTestScriptjs)) If (NotMasterPageClientScriptIsStartupScriptRegistered(alert)) Then MasterPageClientScriptRegisterStartupScript(MeGetType() alertinsideJS() True)

End If End Sub

Using this approach we can avoid referencing the js file for every content pageNote This approach adds the JavaScript reference inside the ltbodygttag of the

page4 Declare JavaScript inside the Content page and execute it

If you are looking out to declare JavaScript inside the Content Page then herersquos howto do so Add the following markup inside the Content page (in our case

Defaultaspx)ltaspContent ID=Content2 ContentPlaceHolderID=ContentPlaceHolder1Runat=Servergt ltaspPanel ID=panelContent GroupingText=ContentPage Controlsrunat=servergt

ltaspTextBox ID=txtContent runat=servergtltaspTextBoxgt ltaspButton ID=btnContent runat=server Text=ButtonOnClientClick=Populate() gt ltaspPanelgt ltscript type=textjavascript language=javascriptgt function Populate()

documentgetElementById(lt=txtContentClientID

gt)value = Hi

ltscriptgtltaspContentgt

The markup shown above populates the textbox with some text on a button click5 Accessing a Control on the Master Page From a ContentPage using

JavaScriptIn our previous article we saw how in Tip 5 To access a control on the ContentPage

From a Master Page using JavaScript In this tip we will see how to access a controlkept on the MasterPage from a ContentPage Do the following

We have added a textbox control to the ltbodygt of the MasterPage as shown belowltbodygt ltform id=form1 runat=servergt ltdivgt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4353

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4453

ASPNET master pages allow you to create a consistent layout for the pages in yourapplication A single master page defines the look and feel and standard behavior thatyou want for all of the pages (or a group of pages) in your application You can thencreate individual content pages that contain the content you want to display When usersrequest the content pages they merge with the master page to produce output thatcombines the layout of the master page with the content from the content page

This overview contains the following sections

bull How Master Pages Work

bull Advantages of Master Pages

bull Run-time Behavior of Master Pages

bull Master Page and Content Page Paths

bull Master Pages and Themes

bull Scoping Master Pages

bull Related Topics

bull Reference

How Master Pages Work

Master pages actually consist of two pieces the master page itself and one or morecontent pages

Note

You can also nest master pages For details see Nested ASPNET Master Pages

Master Pages

A master page is an ASPNET file with the extension master (for example MySitemaster)with a predefined layout that can include static text HTML elements and server controls

The master page is identified by a special Master directive that replaces the Page directive that is used for ordinary aspx pages The directive looks like the following

VBCC++F

JScript

Copylt Master Language=C gt

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4553

The Master directive can contain most of the same directives that a Control directivecan contain For example the following master-page directive includes the name of acode-behind file and assigns a class name to the master page

VBCC++FJScript

Copylt Master Language=C CodeFile=MasterPagemastercsInherits=MasterPage gt

In addition to the Master directive the master page also contains all of the top-levelHTML elements for a page such as html head and form For example on a master pageyou might use an HTML table for the layout an img element for your company logo statictext for the copyright notice and server controls to create standard navigation for yoursite You can use any HTML and any ASPNET elements as part of your master page

Replaceable Content Placeholders

In addition to static text and controls that will appear on all pages the master page alsoincludes one or more ContentPlaceHolder controls These placeholder controls defineregions where replaceable content will appear In turn the replaceable content is definedin content pages After you have defined the ContentPlaceHolder controls a master pagemight look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4653

Copylt Master Language=C gt

ltDOCTYPE html PUBLIC -W3CDTD XHTML11EN httpwwww3orgTRxhtml11DTDxhtml11dtdgt

lthtml xmlns=httpwwww3org1999xhtml gtlthead runat=server gt

lttitlegtMaster page titlelttitlegtltheadgtltbodygt

ltform id=form1 runat=servergtlttablegt

lttrgtlttdgtltaspcontentplaceholder id=Main runat=server gtlttdgtlttdgtltaspcontentplaceholder id=Footer runat=server gtlttdgt

lttrgtlttablegt

ltformgtltbodygtlthtmlgt

Content Pages

You define the content for the master pages placeholder controls by creating individualcontent pages which are ASPNET pages (aspx files and optionally code-behind files)

that are bound to a specific master page The binding is established in the content pages Page directive by including a MasterPageFile attribute that points to the master page tobe used For example a content page might have the following Page directive whichbinds it to the Master1master page

VBC

C++FJScript

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4753

lt Page Language=C MasterPageFile=~MasterPagesMaster1masterTitle=Content Pagegt

In the content page you create the content by adding Content controls and mappingthem to ContentPlaceHolder controls on the master page For example the master pagemight have content placeholders called Main and Footer In the content page you can

create two Content controls one that is mapped to the ContentPlaceHolder control Mainand the other mapped to the ContentPlaceHolder control Footer as shown in the followingfigure

Replacing placeholder content

After creating Content controls you add text and controls to them In a content pageanything that is not inside the Content controls (except script blocks for server code)results in an error You can perform any tasks in a content page that you do in anASPNET page For example you can generate content for a Content control using servercontrols and database queries or other dynamic mechanisms

A content page might look like the following

VBCC++FJScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4853

CopyThis language is not supported or no code example is available

[C]

Copylt Page Language=C MasterPageFile=~Mastermaster Title=Content Page1 gtltaspContent ID=Content1 ContentPlaceHolderID=Main Runat=Servergt

Main contentltaspContentgt ltaspContent ID=Content2 ContentPlaceHolderID=Footer Runat=Server gt

Footer contentltaspcontentgt

The Page directive binds the content page to a specific master page and it defines atitle for the page that will be merged into the master page Note that the content pagecontains no other markup outside of the Content controls (The master page must containa head element with the attribute runat=server so that the title setting can be mergedat run time)

You can create multiple master pages to define different layouts for different parts of yoursite and a different set of content pages for each master page

Back to top

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copyingexisting code text and control elements repeatedly using framesets using include filesfor common elements using ASPNET user controls and so on Advantages of masterpages include the following

bull They allow you to centralize the common functionality of your pages so that youcan make updates in just one place

bull They make it easy to create one set of controls and code and apply the results toa set of pages For example you can use controls on the master page to create a

menu that applies to all pagesbull They give you fine-grained control over the layout of the final page by allowing

you to control how the placeholder controls are rendered

bull They provide an object model that allows you to customize the master page fromindividual content pages

Back to top

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 4953

Run-time Behavior of Master Pages

At run time master pages are handled in the following sequence

1 Users request a page by typing the URL of the content page

2When the page is fetched the Page directive is read If the directive referencesa master page the master page is read as well If this is the first time the pageshave been requested both pages are compiled

3 The master page with the updated content is merged into the control tree of thecontent page

4 The content of individual Content controls is merged into the correspondingContentPlaceHolder control in the master page

5 The resulting merged page is rendered to the browser

The process is illustrated in the following diagram

Master pages at run time

From the users perspective the combined master and content pages are a singlediscrete page The URL of the page is that of the content page

From a programming perspective the two pages act as separate containers for theirrespective controls The content page acts as a container for the master page Howeveryou can reference public master-page members from code in the content page as

described in the next section

Note that the master page becomes a part of the content page In effect the master pageacts in much the same way a user control acts as a child of the content page and as acontainer within that page In this case however the master page is the container for allof the server controls that are rendered to the browser The control tree for a mergedmaster and content page looks something like this

Copy

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5053

PageMaster Page

(Master page markup and controls)ContentPlaceHolder

Content page markup and server controls(Master page markup and controls)

ContentPlaceHolderContent page markup and server controls(Master page markup and controls)

This diagram is simplified if the content page does not have corresponding Contentcontrols the master page might also have markup and controls in the ContentPlaceHolder controls

In general this structure has no effect on how you construct your pages or program themHowever in some cases if you set a page-wide property on the master page it can affectthe behavior of the content page because the master page is the closest parent for thecontrols on the page For example if you set the EnableViewState property on thecontent page to true but set the same property to false in the master page view state willeffectively be disabled because the setting on the master page will take priority

Back to top

Master Page and Content Page Paths

When a content page is requested its content is merged with the master page and thepage runs in the context of the content page For example if you get theCurrentExecutionFilePath property of the HttpRequest object whether in content pagecode or in master page code the path represents the location of the content page

The master page and content page do not have to be in the same folder As long as theMasterPageFile attribute in the content pages Page directive resolves to a master

page ASPNET can merge the content and master pages into a single rendered page

Referencing External Resources

Both the content page and master page can contain controls and elements that referenceexternal resources For example both might contain image controls that reference imagefiles or they might contain anchors that reference other pages

The context for the merged content and master pages is that of the content page Thiscan affect how you specify URLs for resources such as image files and target pages inanchors

Server Controls

In server controls on master pages ASPNET dynamically modifies the URLs of propertiesthat reference external resources For example you might put an Image control on amaster page and set its ImageUrl property to be relative to the master page At run timeASPNET will modify the URL so that it resolves correctly in the context of the contentpage

ASPNET can modify URLs in the following cases

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5153

bull The URL is a property of an ASPNET server control

bull The property is marked internally in the control as being a URL (The property ismarked with the attribute UrlPropertyAttribute) In practical terms ASPNET servercontrol properties that are commonly used to reference external resources aremarked in this way

Other Elements

ASPNET cannot modify URLs on elements that are not server controls For example if youuse an img element on a master page and set its src attribute to a URL ASPNET will notmodify the URL In that case the URL will be resolved in the context of the content pageand create the URL accordingly

In general when working with elements on master pages it is recommended that you usea server control even for elements that do not require server code For example insteadof using an img element use an Image server control That way ASPNET can resolveURLs correctly and you can avoid maintenance issues that might arise if you move themaster or content page

For more information about specifying paths for ASPNET server controls see ASPNETWeb Project Paths

Back to top

Master Pages and Themes

You cannot directly apply an ASPNET theme to a master page If you add a themeattribute to the Master directive the page will raise an error when it runs

However themes are applied to master pages under these circumstances

bullIf a theme is defined in the content page Master pages are resolved in thecontext of content pages so the content pages theme is applied to the masterpage as well

bull If the site as a whole is configured to use a theme by including a theme definitionin the pages Element (ASPNET Settings Schema) element

For more information see ASPNET Themes and Skins

Back to top

Scoping Master Pages

You can attach content pages to a master page at three levels

bull At the page level You can use a page directive in each content page to bind itto a master page as in the following code example

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5253

VB

C

C++

F

JScript

Copy

This language is not supported or no code example is available

VB

C

C++

F

JScript

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server

872019 When a request reaches IIS

httpslidepdfcomreaderfullwhen-a-request-reaches-iis 5353

Copy

lt Page Language=C MasterPageFile=MySiteMaster gt

bull At the application level By making a setting in the pages element of theapplications configuration file (Webconfig) you can specify that all ASPNETpages (aspx files) in the application automatically bind to a master page The

element might look like the following

Copy

ltpages masterPageFile=MySiteMaster gtIf you use this strategy all ASPNET pages in the application that have Content controlsare merged with the specified master page (If an ASPNET page does not contain Contentcontrols the master page is not applied)

bull At the folder level This strategy is like binding at the application level exceptthat you make the setting in a Webconfig file in one folder only The master-pagebindings then apply to the ASPNET pages in that folder

When a request reaches IIS http modules http handler task of web server