Unit V
Unit V
Master pages in ASP.NET work as a template page. All aspx pages can refer
master pages. With the help of Master pages we can define the look and feel of
all the pages in our web site in a single location. If we have done changes in master
page, then the changes will reflect in all the web pages that refer to master
pages.
ASP.NET web page that uses master page for common UI, is called as content
page. Content pages merge with the master pages at compile time to produce final
output. The final page combines the layout of the master page with the content
from the content page.
</asp:ContentPlaceHolder>
The page-specific content is then put inside a Content control that points to the
relevant ContentPlaceHolder:
In this lesson, you will learn about the need for and evolution of master pages in
ASP.NET in Visual Studio IDE. Master pages are created in a website to enhance
modularity and user-friendliness. They help standardize the designing elements
like header, footer, navigation menus, and other parts, which are common to the
entire web site and present on every single page of the web application.
Introduction#
Websites always use some elements repeatedly, like menu logos, headers, footers,
and sidebars. Some developers simply copy and paste the code for the common
elements to every page. This works, but the process is very cumbersome. Every
change to any of the elements needs to be done to each page manually. Formerly,
this was the only way to duplicate the change.
Another more sophisticated way was to include all the common elements into a so-
called ‘include file’. Then a link to this page would be included whereever needed.
Like at the top, the ‘header.aspx’ would be included, and at the bottom,
‘footer.aspx’ would be included. But, closing of the HTML tags was difficult. Web
pages sometimes displayed strange results because of inappropriate, non-existent
tag openings or closings. This made web developers unable to see the whole web
page.
Then, web developers tried using user controls to encapsulate common sections of
their web pages. The Drag-and-Drop technique was used, but the common areas
were displayed only as gray boxes, and visualizing the webpage was not possible.
The issue of matching tags remained the same.
Master pages#
Then, the ASP.NET team developed the idea of master pages: a unique way to
apply templates to web applications. User controls are embedded within the page
and are doomed to duplication. But master pages live outside the aspx page. The
master pages draw distinct lines between the common areas and unique content
areas of each page.
While deploying a master page, you can see the template in the IDE and the
design of the content page in the Design part of the IDE.
Benefits of master pages#
Many people and enterprises find using master pages ideal, as the technology
models their typical business requirements. Since most companies want to apply a
common look and feel across the intranet, they can provide the divisions of the
company with a .master file to use while creating a department’s section of the
intranet.
Once a master page has been defined, it can be bound to new ASP.NET pages
through the tick of a checkbox. These content pages include content placeholder
controls. When the web page is opened in a browser, ASP.NET’s engine creates
the master page’s control hierarchy and injects the control pages hierarchy at the
proper places. This combined control hierarchy is rendered and the resulting
HTML is rendered to the end user’s browser.
MasterPage
A Master Page enables us to share the same content among multiple content pages
in a website. We can use a Master Page to create a common page layout. For
example, if we want all the pages in our website to share a three-column layout,
we can create the layout once in a Master Page and apply the layout to multiple
content pages. We also can use Master Pages to display common content in
multiple pages. For example, if we want to display a standard header and footer in
each page in our website, then we can create the standard header and footer in a
Master Page. By taking advantage of Master Pages, we can make our website
easier to maintain, extend, and modify. If we need to add a new page to our
website that looks just like the other pages in our website, then we simply need to
apply the same Master Page to the new content page. If we decide to completely
modify the design of our website, we do not need to change every content page.
We can modify just a single Master Page to dramatically change the appearance of
all the pages in our application by using CSS. Take a look at the following example
for a better understanding.
A Master Page has the .master extension and we create a Master Page by creating
a file that ends with the .master extension. We can locate a Master Page file
anywhere within an application. We also can add multiple Master Pages to the same
application.
In the above example, the Master Page looks very much like a normal ASP.NET
page. In fact, we can place almost all the same elements in a Master Page that
we can place in an ASP.NET page, including HTML, server-side scripts, and
ASP.NET controls. There are two special things about the Master Page. First, the
file contains a <%@ Master %> directive instead of the normal <%@ Page %>
directive. Second, the Master Page includes a ContentPlaceHolder control which is
for referral by child pages/content pages. When the Master Page is merged with
a particular content page, the content from the content page appears in the areas
marked by the ContentPlaceHolder controls. We can add as many
ContentPlaceHolders to a Master Page as we need.
The Master Page given below has a two-column page layout. Each
ContentPlaceHolder control is contained in a separate <div> tag. Cascading Style
Sheet (CSS) rules are used to position the two <div> tags into a two-column page
layout.
The content page, which uses a Master Page is given below:
When we open the preceding page in a web browser, the contents of the page are
merged with the Master Page. The Master Page is associated with the content
page through the MasterPageFile attribute included in the <%@ Page %> directive.
This attribute contains the virtual path to a Master Page. The content page does
not contain any of the standard opening and closing XHTML tags. All these tags
are contained in the Master Page. All the content contained in the content page
must be added with Content controls. We must place all the content contained in a
content page within the Content controls. If we attempt to place any content
outside these controls, we get an exception. The Content control includes a
ContentPlaceHolderID property. This property points to the ID of a
ContentPlaceHolder control contained in the Master Page. Within a Content
control, we can place anything that we would normally add to an ASP.NET page,
including XHTML tags and ASP.NET controls.
https://www.completecsharptutorial.com/mvc-articles/mvc-design-master-page-
layout-with-css-html-template.php
https://www.tutorialspoint.com/adobe_robohelp/adobe_robohelp_creating_worki
ng_on_master_pages.htm
Every ASP.NET developer needs to be familiar with Page Directives. If you are a
beginner and you want to learn about the Page Directives then you can read this
article.
So the first question is about Page Directives.
Basically, Page Directives are commands. These commands are used by the
compiler when the page is compiled.
<%@[Directive][Attributes]%>
See the directive format, it starts with "<%@" and ends with "%>". The best way
is to put the directive at the top of your page. But you can put a directive
anywhere in a page. One more thing, you can put more than one attribute in a
single directive.
• @Page
• @Master
• @Control
• @Import
• @Implements
• @Register
• @Assembly
• @MasterType
• @Output Cache
• @PreviousPageType
• @Reference
@Page
When you want to specify the attributes for an ASP.NET page then you need to
use @Page Directive. As you know, an ASP.NET page is a very important part of
ASP.NET, so this directive is commonly used in ASP.NET.
Example:
@Master
Now you have some information about @Page Directives. The @Master Directive
is quite similar to the @Page Directive. The only difference is that the @master
directive is for Master pages. You need to note that, while using the @Master
Directive you define the template page's property. Then any content page can
inherit all the properties defined in the Master Page. But there are some
properties that are only available in a Master Page.
Example
@Control
@Control builds ASP.NET user controls. When you use the directive you define
the properties to be inherited by the user controls and theses values are assigned
to the user controls
Example:
@Import
As you know you need to define namespaces in your .cs class before using a C# or
VB class. So the @Import Directive imports namespaces. This directive supports
just a single attribute "namespace" and this attribute takes a string value that
specifies the namespace to be imported. One thing you need to note is that the
@Import Directive cannot contain more than one attribute/value pair. But you
can use multiple lines.
Example:
1. <%@Import Namespace="System.Data"%>
@Implements
Example:
1. <%@Implements Interface="System.Web.UI.IValidator"%>
@Register
When you create a user control and you drag that user control onto your page
then you will see the @Register directive. This directive registers your user
control on the page so that the control can be accessed by the page.
Example:
@Assembly
Example:
1. <%@Assembly Name="MyAssembly"%>
2. <%@Assembly src="MYAssembly.cs">
@MasterType
The @MasterType Directive connects a class name to the ASP.NET page for
getting strongly typed references or members contained in the specified Master
Page. This directive supports the two attributes Typename and virtualpath.
Typename sets the name of the derived class from which to get the strongly
typed or reference members and virtualpath sets the location of the page from
which these are retrieved.
Example:
1. <%@MasterType VirtualPath="/MasterPage1.master"%>
@output cache
Example:
@Previouspagetype
This directive specifies the page from which any cross-page posting originates.
@Reference
This directive declares that another page or user control shout be complied along
with the active page or control. This directive supports the single attribute
virtualpath. It sets the location of the page or user control from which the active
page will be referenced.
Example:
1. <%@Reference VirtualPayh="~/MyControl.ascx"%>
Final Words
I hope you get some knowledge from here. Please comment about how you like this
article. Your comments are very valuable for me, because only you will tell me
where I am going wrong and what improvements I need to make to write a better
article. Please comment and provide your feedback.
https://docs.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-
getting-started/master-pages/multiple-contentplaceholders-and-default-content-
cs
Introduction
Themes are also a new feature of ASP.NET that helps maintain a consistent look
and feel across all or several pages of our web site. Themes are needed when we
want to keep the style and layout information files separate from other web site
files. A theme is a collection of settings that define the look of controls and web
pages. These themes are applied across all the pages in a web application to
maintain a consistent appearance. Themes are included images and skin files; the
skin files set the visual properties of ASP.NET controls. Themes are of two types:
Page Theme
A Page theme contains the control skins, style sheets, graphic files, and other
resources inside the subfolder of the App_Theme folder in the Solution Explorer
window. A page theme is applied to a single page of the web site.
Global Theme
A Global theme is a theme that is applied to all the web sites on a web server and
includes property settings, and graphics. This theme allows us to maintain all the
websites on the same web server and define the same style for all the web pages
of the web sites.
Let's create a theme application with the help of the following steps:
Step 4 : Now right-click in the application name in the Solution Explorer window
and select Add
ASP.NET Folder->Theme from the context menu.
Step 6 : Select the Skin file and click the Add button.
Output :
Now we will create an application for applying the theme at run time.
Step 9 : To do this add another skin file to the application and write the
following code for both skin files.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
void Page_PreInit(object sender, EventArgs e)
{
// Get the theme name from a QueryString variable
string ThemeName;
ThemeName = Request.QueryString["Theme"];
if (ThemeName != null)
{
Page.Theme = ThemeName;
}
}
}
Output :
A cookie is a small bit of text that accompanies requests and pages as they go
between the Web server and browser. The cookie contains information the Web
application can read whenever the user visits the site.
Scenarios
Background
A cookie is a small bit of text that accompanies requests and pages as they go
between the Web server and browser. The cookie contains information the Web
application can read whenever the user visits the site.
For example, if a user requests a page from your site and your application sends
not just a page, but also a cookie containing the date and time, when the user's
browser gets the page, the browser also gets the cookie, which it stores in a
folder on the user's hard disk.
Later, if user requests a page from your site again, when the user enters the URL
the browser looks on the local hard disk for a cookie associated with the URL. If
the cookie exists, the browser sends the cookie to your site along with the page
request. Your application can then determine the date and time that the user last
visited the site. You might use the information to display a message to the user or
check an expiration date.
Cookies are associated with a Web site, not with a specific page, so the browser
and server will exchange cookie information no matter what page the user
requests from your site. As the user visits different sites, each site might send a
cookie to the user's browser as well; the browser stores all the cookies
separately.
Cookies help Web sites store information about visitors. More generally, cookies
are one way of maintaining continuity in a Web application—that is, of performing
state management. Except for the brief time when they are actually exchanging
information, the browser and Web server are disconnected. Each request a user
makes to a Web server is treated independently of any other request. Many
times, however, it's useful for the Web server to recognize users when they
request a page. For example, the Web server on a shopping site keeps track of
individual shoppers so the site can manage shopping carts and other user-specific
information. A cookie therefore acts as a kind of calling card, presenting
pertinent identification that helps an application know how to proceed.
Cookies are used for many purposes, all relating to helping the Web site
remember users. For example, a site conducting a poll might use a cookie simply as
a Boolean value to indicate whether a user's browser has already participated in
voting so that the user cannot vote twice. A site that asks a user to log on might
use a cookie to record that the user already logged on so that the user does not
have to keep entering credentials.
Cookie Limitations
Most browsers support cookies of up to 4096 bytes. Because of this small limit,
cookies are best used to store small amounts of data, or better yet, an identifier
such as a user ID. The user ID can then be used to identify the user and read
user information from a database or other data store. (See the section "Cookies
and Security" below for information about security implications of storing user
information.)
Browsers also impose limitations on how many cookies your site can store on the
user's computer. Most browsers allow only 20 cookies per site; if you try to store
more, the oldest cookies are discarded. Some browsers also put an absolute limit,
usually 300, on the number of cookies they will accept from all sites combined.
A cookie limitation that you might encounter is that users can set their browser
to refuse cookies. If you define a P3P privacy policy and place it in the root of
your Web site, more browsers will accept cookies from your site. However, you
might have to avoid cookies altogether and use a different mechanism to store
user-specific information. A common method for storing user information is
session state, but session state depends on cookies, as explained later in the
section "Cookies and Session State."
Although cookies can be very useful in your application, the application should not
depend on being able to store cookies. Do not use cookies to support critical
features. If your application must rely on cookies, you can test to see whether the
browser will accept cookies. See the "Checking Whether a Browser Accepts
Cookies" section later in this topic.
Writing Cookies
The browser is responsible for managing cookies on a user system. Cookies are
sent to the browser via the HttpResponse object that exposes a collection
called Cookies. You can access the HttpResponse object as the Response property
of your Page class. Any cookies that you want to send to the browser must be
added to this collection. When creating a cookie, you specify a Name and Value.
Each cookie must have a unique name so that it can be identified later when
reading it from the browser. Because cookies are stored by name, naming two
cookies the same will cause one to be overwritten.
You can also set a cookie's date and time expiration. Expired cookies are deleted
by the browser when a user visits the site that wrote the cookies. The expiration
of a cookie should be set for as long as your application considers the cookie value
to be valid. For a cookie to effectively never expire, you can set the expiration
date to be 50 years from now.
If you do not set the cookie's expiration, the cookie is created but it is not
stored on the user's hard disk. Instead, the cookie is maintained as part of the
user's session information. When the user closes the browser, the cookie is
discarded. A non-persistent cookie like this is useful for information that needs
to be stored for only a short time or that for security reasons should not be
written to disk on the client computer. For example, non-persistent cookies are
useful if the user is working on a public computer, where you do not want to write
the cookie to disk.
You can add cookies to the Cookies collection in a number of ways. The following
example shows two methods to write cookies:
VBCopy
Response.Cookies("userName").Value = "patrick"
Response.Cookies("userName").Expires = DateTime.Now.AddDays(1)
DimaCookieAsNewHttpCookie("lastVisit")
aCookie.Value = DateTime.Now.ToString()
aCookie.Expires = DateTime.Now.AddDays(1)
Response.Cookies.Add(aCookie)
The example adds two cookies to the Cookies collection, one named userName and
the other named lastVisit. For the first cookie, the values of
the Cookies collection are set directly. You can add values to the collection this
way because Cookies derives from a specialized collection of
type NameObjectCollectionBase.
Both examples accomplish the same task, writing a cookie to the browser. In both
methods, the expiration value must be of type DateTime. However, the lastVisited
value is also a date-time value. Because all cookie values are stored as strings, the
date-time value has to be converted to a String .
You can store one value in a cookie, such as user name and last visit. You can also
store multiple name-value pairs in a single cookie. The name-value pairs are
referred to as subkeys. (Subkeys are laid out much like a query string in a URL.)
For example, instead of creating two separate cookies named userName and
lastVisit, you can create a single cookie named userInfo that has the
subkeysuserName and lastVisit.
You might use subkeys for several reasons. First, it is convenient to put related or
similar information into a single cookie. In addition, because all the information is
in a single cookie, cookie attributes such as expiration apply to all the information.
(Conversely, if you want to assign different expiration dates to different types of
information, you should store the information in separate cookies.)
A cookie with subkeys also helps you limit the size of cookie files. As noted earlier
in the "Cookie Limitations" section, cookies are usually limited to 4096 bytes and
you can't store more than 20 cookies per site. By using a single cookie with
subkeys, you use fewer of those 20 cookies that your site is allotted. In addition,
a single cookie takes up about 50 characters for overhead (expiration information,
and so on), plus the length of the value that you store in it, all of which counts
toward the 4096-byte limit. If you store five subkeys instead of five separate
cookies, you save the overhead of the separate cookies and can save around
200 bytes.
To create a cookie with subkeys, you can use a variation of the syntax for writing
a single cookie. The following example shows two ways to write the same cookie,
each with two subkeys:
VBCopy
Response.Cookies("userInfo")("userName") = "patrick"
Response.Cookies("userInfo")("lastVisit") = DateTime.Now.ToString()
Response.Cookies("userInfo").Expires = DateTime.Now.AddDays(1)
DimaCookieAsNewHttpCookie("userInfo")
aCookie.Values("userName") = "patrick"
aCookie.Values("lastVisit") = DateTime.Now.ToString()
aCookie.Expires = DateTime.Now.AddDays(1)
Response.Cookies.Add(aCookie)
Controlling Cookie Scope
By default, all cookies for a site are stored together on the client, and all cookies
are sent to the server with any request to that site. In other words, every page in
a site gets all of the cookies for that site. However, you can set the scope of
cookies in two ways:
• Limit the scope of cookies to a folder on the server, which allows you to limit
cookies to an application on the site.
• Set scope to a domain, which allows you to specify which subdomains in a
domain can access a cookie.
To limit cookies to a folder on the server, set the cookie's Path property, as in
the following example:
VBCopy
DimappCookieAsNewHttpCookie("AppCookie")
appCookie.Value = "written "&DateTime.Now.ToString()
appCookie.Expires = DateTime.Now.AddDays(1)
appCookie.Path = "/Application1"
Response.Cookies.Add(appCookie)
The HttpApplicationState instance is created the first time a user accesses any
URL resource in an application. The HttpApplicationState class is most often
accessed through the Application property of the HttpContext class.
You can use application state in two ways. You can add, access, or remove values
from the Contents collection directly through code.
The HttpApplicationState class can be accessed at any time during the life of an
application. However, it is often useful to load application state data when the
application starts. To do so, you can put code to load application state into the
Application_Start method in the Global.asax file. For more information
see ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0.
Alternatively, you can add objects to the StaticObjects collection via an <object
runat="server"> declaration in your Web application's Global.asax file. Application
state defined in this way can then be accessed from code anywhere in your
application. The following example shows an object declaration for an application
state value:
Copy
You can add objects to the StaticObjects collection only in the Global.asax file.
The collection throws a NotSupportedException if you attempt to add objects
directly through code.
You can access members of objects stored in application state without having to
reference the Application collection. The following code example shows how to
reference a member of an object defined in the StaticObjects collection of
application state. Notice that the label identifier that is defined in the
Global.asax file is used as the variable name.
VBCopy
When using application state, you must be aware of the following important
considerations:
ASP.NET session state enables you to store and retrieve values for a user as the
user navigates ASP.NET pages in a Web application. HTTP is a stateless protocol.
This means that a Web server treats each HTTP request for a page as an
independent request. The server retains no knowledge of variable values that were
used during previous requests. ASP.NET session state identifies requests from
the same browser during a limited time window as a session, and provides a way to
persist variable values for the duration of that session. By default, ASP.NET
session state is enabled for all ASP.NET applications.
• Application state, which stores variables that can be accessed by all users of
an ASP.NET application.
• Profile properties, which persists user values in a data store without expiring
them.
• ASP.NET caching, which stores values in memory that is available to all
ASP.NET applications.
• View state, which persists values in a page.
• Cookies.
• The query string and fields on an HTML form that are available from an HTTP
request.
Session Variables
VBCopy
Session("FirstName") = FirstNameTextBox.Text
Session("LastName") = LastNameTextBox.Text
Session variables can be any valid .NET Framework type. The following example
stores an ArrayList object in a session variable named StockPicks. The value
returned by the StockPicks session variable must be cast to the appropriate type
when you retrieve it from the SessionStateItemCollection.
VBCopy
' Write the modified stock picks list back to session state.
Session("StockPicks") = stockPicks
Session Identifiers
By default, SessionID values are stored in a cookie. However, you can also
configure the application to store SessionID values in the URL for a "cookieless"
session.
By default, the session ID values that are used in cookieless sessions are
recycled. That is, if a request is made with a session ID that has expired, a new
session is started by using the SessionID value that is supplied with the request.
This can result in a session unintentionally being shared when a link that contains a
cookieless SessionID value is used by multiple browsers. (This can occur if the link
is passed through a search engine, through an e-mail message, or through another
program.) You can reduce the chance of session data being shared by configuring
the application not to recycle session identifiers. To do this, set the
regenerateExpiredSessionId attribute of the sessionState configuration element
to true. This generates a new session ID when a cookieless session request is
made with an expired session ID.