0% found this document useful (0 votes)
57 views17 pages

The Page Class

The document provides an overview of the Page, HttpRequest, and HttpResponse classes in ASP.NET, detailing their properties and methods for managing web pages, handling user requests, and sending responses. It emphasizes the Page class as the foundation for web pages, while the HttpRequest class captures incoming data and the HttpResponse class controls the outgoing data. Key properties and examples are included to illustrate how developers can utilize these classes effectively.

Uploaded by

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

The Page Class

The document provides an overview of the Page, HttpRequest, and HttpResponse classes in ASP.NET, detailing their properties and methods for managing web pages, handling user requests, and sending responses. It emphasizes the Page class as the foundation for web pages, while the HttpRequest class captures incoming data and the HttpResponse class controls the outgoing data. Key properties and examples are included to illustrate how developers can utilize these classes effectively.

Uploaded by

Indira pothiraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

THE PAGE CLASS

 Every web page is a custom class that inherits from the System.
Web. UI. Page control.
 The Page class in ASP.NET is the base class for all webpages in a web
application.
 It provides properties, methods, and events to manage the webpage's
lifecycle, handle user interactions, and control the rendering of the
page.
 The Page class allows developers to access request and response data,
manage user sessions, and interact with server-side controls.
 It simplifies tasks such as form submission, user authentication, and
dynamic content generation.
 The Page class ensures that webpages are processed on the server
and delivered to the client's browser efficiently.

Basic Page Properties:


Property Description Example

Sets or gets
the title of
the webpage.
This appears
Title Page.Title = "My Cool Game Page";
in the
browser's
title bar or
tab.

Checks if the
page is being
loaded in
if (!Page.IsPostBack) { /* Do something on first load
IsPostBack response to a
*/ }
postback (like
a form
submission).

Provides
information
about the
current web
Request string userName = Page.Request.QueryString["name"];
request, such
as query
strings or
form data.

Response Represents Page.Response.Write("Hello, World!");


the current
web response
Property Description Example

and is used
to send
output to the
client.

Manages
user-specific
data that
persists
Session across Page.Session["user"] = "JohnDoe";
multiple
pages (like a
shopping
cart).

Allows storing
and
retrieving
Cache Page.Cache["time"] = DateTime.Now;
data that can
be reused for
faster access.

Provides a
collection of
Controls all the Control myButton = Page.Controls[0];
controls on
the page.

Used to
register and
emit client-
Page.ClientScript.RegisterStartupScript(this.GetType(),
ClientScript side scripts
"alert", "alert('Hello!');", true);
(JavaScript)
to the
webpage.

Determines
whether the
page
EnableViewStat
maintains its Page.EnableViewState = true;
e
state (data)
across
postbacks.

Server Provides string serverPath = Page.Server.MapPath("~");


methods and
properties for
handling
Property Description Example

server-side
operations
and
information.

Represents
the currently
authenticate
d user,
User providing string userName = Page.User.Identity.Name;
information
about the
user’s
identity.

Quick Breakdown
1. Title: Sets the text that appears in the browser tab.
o Example: Page.Title = "My Cool Game Page";
o What It Does: Sets the tab title to "My Cool Game Page".
2. IsPostBack: Checks if the page is reloaded due to a user action like
clicking a button.
o Example: if (!Page.IsPostBack) { /* Do something on first load */
}
o What It Does: Runs code only the first time the page loads.
3. Request: Gets information sent to the page, like form data.
o Example: string userName =
Page.Request.QueryString["name"];
o What It Does: Gets the value of the query string parameter
"name".
4. Response: Sends information back to the user's browser.
o Example: Page.Response.Write("Hello, World!");
o What It Does: Displays "Hello, World!" on the webpage.
5. Session: Stores user-specific information for use across different
pages.
o Example: Page.Session["user"] = "JohnDoe";
o What It Does: Saves the user name "JohnDoe" in the session.
6. Cache: Stores data to make future requests faster.
o Example: Page.Cache["time"] = DateTime.Now;
o What It Does: Saves the current time in the cache.
7. Controls: Lists all the elements (like buttons and text boxes) on the
page.
o Example: Control myButton = Page.Controls[0];
o What It Does: Gets the first control on the page.
8. ClientScript: Adds JavaScript code to the page.
o Example:
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert",
"alert('Hello!');", true);
o What It Does: Shows a pop-up alert saying "Hello!" when the
page loads.
9. EnableViewState: Determines if the page keeps its data between
postbacks.
o Example: Page.EnableViewState = true;
o What It Does: Keeps the page's data when you submit a form.
10. Server: Helps with server-side tasks like file paths and URL
encoding.
o Example: string serverPath = Page.Server.MapPath("~");
o What It Does: Gets the server path to the root of the
application.
11. User: Information about the logged-in user.
o Example: string userName = Page.User.Identity.Name;
o What It Does: Gets the name of the currently logged-in user.

The HttpRequest Class


The HttpRequest class in ASP.NET is like a mailbox that collects all the
information sent to your web server whenever someone visits your webpage.
This class holds details about the request, such as what the user typed in the
URL, any data they submitted through a form, and even the type of device
they're using to browse your site.
HttpRequest Properties
Property Description Example

Gets the
values of the
QueryString query string string id = Request.QueryString["id"];
parameters in
the URL.

Gets the
values
submitted in a
Form string name = Request.Form["name"];
form (like text
input or
selections).

Gets the
cookies sent
Cookies HttpCookie cookie = Request.Cookies["user"];
by the
browser.

Gets all the


header
string userAgent = Request.Headers["User-
Headers information
Agent"];
sent by the
browser.

Gets the HTTP


method (GET,
HttpMethod POST, etc.) string method = Request.HttpMethod;
used by the
client.

Gets the full


URL of the
Url string currentUrl = Request.Url.ToString();
current
request.

Gets the URL


of the
previous page
UrlReferrer string referrer = Request.UrlReferrer.ToString();
that linked to
the current
request.

Gets the IP
address of the
UserHostAddress string userIp = Request.UserHostAddress;
client (the
user's device).
Property Description Example

Gets the DNS


name of the
UserHostName string userHostName = Request.UserHostName;
client (the
user's device).

Gets the files


Files uploaded by HttpPostedFile file = Request.Files["fileUpload"];
the client.

Determines
whether the
page
EnableViewState maintains its Page.EnableViewState = true;
state (data)
across
postbacks.

Provides
methods and
properties for
handling
Server string serverPath = Page.Server.MapPath("~");
server-side
operations
and
information.

Represents
the currently
authenticated
user,
User providing string userName = Page.User.Identity.Name;
information
about the
user’s
identity.

Gets the
virtual
ApplicationPath application string appPath = Request.ApplicationPath;
root path on
the server.

PhysicalPath Gets the string physPath = Request.PhysicalPath;


physical file
system path
corresponding
to the
requested
Property Description Example

URL.

Checks if the
user has been
IsAuthenticated bool isAuthenticated = Request.IsAuthenticated;
authenticated
.

Checks if the
IsSecureConnectio request is
bool isSecure = Request.IsSecureConnection;
n being made
over HTTPS.

Gets a
collection of
variables string serverSoftware =
ServerVariables
provided by Request.ServerVariables["SERVER_SOFTWARE"];
the web
server.

Quick Breakdown
1. QueryString: Captures the information after the "?" in the URL.
o Example: If the URL is http://example.com/page?name=John,
you can get "John" with Request.QueryString["name"];
2. Form: Captures data submitted through a form on the webpage.
o Example: If a form has an input field named "name", you can
get its value with Request.Form["name"];
3. Cookies: Stores small pieces of data sent by the browser, like user
preferences.
o Example: If a cookie named "user" is set, you can get it with
Request.Cookies["user"];
4. Headers: Contains information about the client's request, like the
browser type.
o Example: You can get the browser information with
Request.Headers["User-Agent"];
5. HttpMethod: Tells you whether the request is a GET, POST, etc.
o Example: string method = Request.HttpMethod; might return
"GET" or "POST".
6. Url: The full address of the webpage being requested.
o Example: string currentUrl = Request.Url.ToString(); could be
http://example.com/page.
7. UrlReferrer: The address of the previous page that linked to the
current page.
o Example: string referrer = Request.UrlReferrer.ToString(); might
be http://example.com/home.
8. UserHostAddress: The IP address of the user making the request.
o Example: string userIp = Request.UserHostAddress; might
return something like 192.168.1.1.
9. UserHostName: The DNS name of the user making the request.
o Example: string userHostName = Request.UserHostName;
might return something like host.example.com.
10. Files: Manages file uploads from the client.
o Example: If a form has a file input named "fileUpload", you can
get the uploaded file with Request.Files["fileUpload"];
11. EnableViewState: Determines if the page keeps its data
between postbacks.
o Example: Page.EnableViewState = true;
o What It Does: Keeps the page's data when you submit a form.
12. Server: Helps with server-side tasks like file paths and URL
encoding.
o Example: string serverPath = Page.Server.MapPath("~");
o What It Does: Gets the server path to the root of the
application.
13. User: Information about the logged-in user.
o Example: string userName = Page.User.Identity.Name;
o What It Does: Gets the name of the currently logged-in user.
14. ApplicationPath: The virtual path of the application on the
server.
o Example: string appPath = Request.ApplicationPath;
o What It Does: Gets the root path of the application, like
/MyApp.
15. PhysicalPath: The physical file system path corresponding to
the requested URL.
o Example: string physPath = Request.PhysicalPath;
o What It Does: Gets the actual file path on the server, like C:\
Websites\MyApp\index.aspx.
16. IsAuthenticated: Checks if the user is logged in.
o Example: bool isAuthenticated = Request.IsAuthenticated;
o What It Does: Returns true if the user is authenticated, false
otherwise.
17. IsSecureConnection: Checks if the request is made over
HTTPS.
o Example: bool isSecure = Request.IsSecureConnection;
o What It Does: Returns true if the connection is secure (HTTPS),
false otherwise.
18. ServerVariables: A collection of server-specific variables.
o Example: string serverSoftware =
Request.ServerVariables["SERVER_SOFTWARE"];
o What It Does: Gets information like the web server software
being used.
These properties give you powerful ways to interact with and respond to the
requests made to your web application, making it easier to build dynamic
and responsive web pages.

How It Works
When someone visits your website, their browser sends a request to
your server. The HttpRequest class catches this request and lets you access
all the information it carries. This way, you can react to what the user wants
to do, like showing a specific webpage, processing form data, or customizing
the user experience based on their input.
In short, the HttpRequest class is your way of understanding and reacting to
what users are asking for when they interact with your website.

HttpResponse Class
The HttpResponse class in ASP.NET is like a mailbox that sends information
back to the user's browser after the server processes a request. This class
lets you control what gets sent back, such as the webpage content, cookies,
or special instructions for the browser.

HttpResponse Properties
Property/ Descriptio
Example
Method n

Enables or
disables
BufferOutput buffering of Response.BufferOutput = true;
the
response.

Manages
cache-
specific
headers to
Response.Cache.SetExpires(DateTime.Now.AddMinutes(10
Cache control how
));
documents
are cached
on the
network.

Manages
cookies that
Cookies Response.Cookies["user"].Value = "JohnDoe";
are sent to
the client.

Writes a
string of
text directly
Write() to the Response.Write("Hello, World!");
response
output
stream.

Writes a
byte array
directly to
byte[] data = { 0x0, 0x1, 0x2 };
BinaryWrite() the
Response.BinaryWrite(data);
response
output
stream.

Writes the
content of a
file directly
WriteFile() to the Response.WriteFile("path/to/file.txt");
response
output
stream.

Redirect() Redirects Response.Redirect("http://example.com");


the client to
Property/ Descriptio
Example
Method n

a different
URL.

Quick Breakdown
1. BufferOutput: Controls whether the response is buffered.
o Example: Response.BufferOutput = true;
o What It Does: Enables buffering so the content is sent only
after the response is fully ready.
2. Cache: Manages how the response is cached by the client and proxy
servers.
o Example:
Response.Cache.SetExpires(DateTime.Now.AddMinutes(10));
o What It Does: Sets the expiration time for the cached response
to 10 minutes from now.
3. Cookies: Manages cookies to store small pieces of data on the client's
browser.
o Example: Response.Cookies["user"].Value = "JohnDoe";
o What It Does: Creates a cookie named "user" with the value
"JohnDoe".
4. Write(): Writes a string directly to the response output stream.
o Example: Response.Write("Hello, World!");
o What It Does: Displays "Hello, World!" on the webpage.
5. BinaryWrite(): Writes a binary data array directly to the response
output stream.
o Example: byte[] data = { 0x0, 0x1, 0x2 };
Response.BinaryWrite(data);
o What It Does: Sends binary data to the client.
6. WriteFile(): Writes the contents of a specified file directly to the
response.
o Example: Response.WriteFile("path/to/file.txt");
o What It Does: Sends the contents of "file.txt" to the client.
7. Redirect(): Redirects the user to a different URL.
o Example: Response.Redirect("http://example.com");
o What It Does: Redirects the user to "http://example.com".
How It Works
The HttpResponse class allows you to control what information gets sent
back to the user's browser. By using its properties and methods, you can:
 BufferOutput: Decide if the response should be sent in chunks or all
at once.
 Cache: Manage how the browser and proxies cache the response.
 Cookies: Set cookies to store data on the client's machine.
 Write(): Send plain text data.
 BinaryWrite(): Send binary data.
 WriteFile(): Send the content of a file.
 Redirect(): Redirect the browser to a different URL.
This helps you create dynamic, responsive, and interactive web applications.

ServerUtility Class
The ServerUtility class, often accessed through the Server property of
a web page or application, provides various utility methods that help with
server-side processing. These methods assist with tasks such as URL
encoding, path mapping, and error handling.

ServerUtility Methods
Descri
Method Example
ption

Convert
sa
string
into a
HtmlEnc string encoded =
format
ode() Server.HtmlEncode("<script>alert('hi');</script>");
that is
safe for
use in
HTML.

HtmlDec Convert string decoded =


ode() sa Server.HtmlDecode("&lt;script&gt;alert('hi');&lt;/script&gt;");
string
that
has
been
Descri
Method Example
ption

HTML-
encode
d back
to its
original
form.

Convert
sa
string
into a
UrlEnco string encodedUrl = Server.UrlEncode("http://example.com?
format
de() name=John Doe");
that is
safe for
use in a
URL.

Convert
sa
URL-
string decodedUrl =
encode
UrlDeco Server.UrlDecode("http%3A%2F
d string
de() %2Fexample.com%3Fname
back to
%3DJohn+Doe");
its
original
form.

Convert
sa
virtual
(web)
MapPat path to
string physicalPath = Server.MapPath("/images/photo.jpg");
h() a
physica
l
(server)
path.

Transfer Transfe Server.Transfer("AnotherPage.aspx");


() rs
executi
on to
another
page
on the
server
Descri
Method Example
ption

without
making
a
round-
trip
back to
the
client's
browser
.

Retriev
es the
last
error
GetLast
that Exception lastError = Server.GetLastError();
Error()
occurre
d on
the
server.

Clears
the
error
informa
ClearErr
tion for Server.ClearError();
or()
the
current
request
.

Instanti
ates a
COM
CreateO
object object comObject = Server.CreateObject("ProgID");
bject()
identifi
ed by a
ProgID.

Quick Breakdown
1. HtmlEncode(): Converts characters to HTML-safe characters.
o Example: string encoded =
Server.HtmlEncode("<script>alert('hi');</script>");
o What It Does: Converts < to &lt;, > to &gt;, and so on.
2. HtmlDecode(): Converts HTML-encoded characters back to their
original form.
o Example: string decoded =
Server.HtmlDecode("&lt;script&gt;alert('hi');&lt;/script&gt;");
o What It Does: Converts &lt; back to <, &gt; back to >, etc.
3. UrlEncode(): Converts a string into a URL-friendly format.
o Example: string encodedUrl =
Server.UrlEncode("http://example.com?name=John Doe");
o What It Does: Converts spaces to + and special characters to
%xx format.
4. UrlDecode(): Converts a URL-encoded string back to its original form.
o Example: string decodedUrl = Server.UrlDecode("http%3A%2F
%2Fexample.com%3Fname%3DJohn+Doe");
o What It Does: Converts %xx format back to special characters.
5. MapPath(): Converts a web path to a physical file path on the server.
o Example: string physicalPath =
Server.MapPath("/images/photo.jpg");
o What It Does: Maps /images/photo.jpg to something like C:\
Websites\MyApp\images\photo.jpg.
6. Transfer(): Transfers execution to another page on the server without
a client round-trip.
o Example: Server.Transfer("AnotherPage.aspx");
o What It Does: Stops processing the current page and starts
processing "AnotherPage.aspx".
7. GetLastError(): Retrieves the last server error.
o Example: Exception lastError = Server.GetLastError();
o What It Does: Gets information about the most recent error
that occurred on the server.
8. ClearError(): Clears the current error information.
o Example: Server.ClearError();
o What It Does: Clears the error so it doesn't get processed
further.
9. CreateObject(): Instantiates a COM object identified by a ProgID.
o Example: object comObject = Server.CreateObject("ProgID");
o What It Does: Creates an instance of a COM object based on its
ProgID, allowing interaction with external components.
How It Works
The ServerUtility class in ASP.NET provides essential methods
(HtmlEncode, HtmlDecode, UrlEncode, UrlDecode, MapPath, Transfer,
GetLastError, ClearError, CreateObject) that help developers manage various
server-side tasks efficiently. These methods are crucial for handling URL
encoding, file paths, error handling, and even interfacing with COM objects,
making them indispensable for building robust web applications.

Assessing HTML Server Controls


HTML Server Controls in ASP.NET are like regular HTML elements (like
<input>, <button>, <select>, etc.) but with an additional runat="server"
attribute. This attribute enables them to be treated as server-side controls,
meaning they can be manipulated and controlled using server-side code (C#
or VB.NET) in addition to client-side scripting (JavaScript).
Key Features and Examples
Here are some key features of HTML Server Controls:
1. Server-side Events: HTML Server Controls can trigger server-side
events like Click, TextChanged, SelectedIndexChanged, etc., allowing
you to respond to user actions directly on the server.
Example:
html
Copy code
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
C# Code-behind:
csharp
Copy code
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Server-side code to handle button click event
// This method executes when the button is clicked
}
2. ViewState: HTML Server Controls automatically manage their state
across postbacks using ViewState. This means you can preserve data
and control states between requests without manually handling them.
3. Rich Control Properties: They offer rich properties and methods
specific to each control type (Text, Value, SelectedValue, Checked,
etc.), making it easy to manipulate and retrieve data.
4. Validation Controls: ASP.NET provides built-in validation controls
(RequiredFieldValidator, RegularExpressionValidator, etc.) that work
seamlessly with HTML Server Controls to enforce data entry rules on
the server side.
5. Integration with Client-side Scripting: You can use JavaScript and
jQuery alongside HTML Server Controls to enhance client-side
interactivity while still leveraging server-side capabilities for more
complex tasks.
HTML Server Controls in ASP.NET blend the flexibility of HTML with the
power of server-side processing, offering a robust way to build interactive
web applications. They simplify development by providing seamless
integration with server-side code, state management, and validation,
enabling developers to create responsive and dynamic web experiences
efficiently.

You might also like