ASP.NET.in.a.Nutshell.Second.Edition [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

ASP.NET.in.a.Nutshell.Second.Edition [Electronic resources] - نسخه متنی

G. andrew Duthie; matthew Macdonald

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید










12.2 Properties Reference


Application

HttpApplicationState = Page.Application

Returns an instance of the
HttpApplicationState
class, which is the equivalent of the ASP intrinsic Application
object. An instance of the HttpApplicationState
class contains global information that can be shared across multiple
sessions and requests within an ASP.NET application. For more
information on the HttpApplicationState class and
its members, see Chapter 13.

Parameter


HttpApplicationState



A variable of type HttpApplicationState that receives the instance of
the HttpApplicationState class.



Example


The following code example uses Page object's
Application property to add a name/value pair to the Application
object and display the value in a label control. Since all of the
properties of the Page object are exposed directly to any code
associated with the page, it is not necessary to name the
Page class explicitly (i.e.,
Page.Application) to access the Application
property.

Sub Page_Load( )
Application("Name") = "John Doe"
Message.Text = "The value <em>" & CStr(Application("Name")) & _
"</em> has been added to the Application collection."
End Sub

Notes


Although you can retrieve a local object reference to the
HttpApplicationState instance for the application, the more common
use of this property is to access it directly through the Application
property, as shown in the example.

Cache

Cache = Page.Cache

Returns an instance of the
Cache class, which represents the cache for an
application domain. Using the Cache property, data can be added to
and retrieved from the cache.

Parameter


Cache



A variable of type Cache that will receive the Cache instance.



Example


The following code example adds two name/value pairs to the Cache
object using the Cache property of the Page class
and displays the values in a label control using the Page
object's Cache property:

Sub Page_Load(o As Object, e As EventArgs)
Cache("Name") = "John Doe"
Cache("Age") = 42
Message.Text = CStr(Cache.Item("Name")) & " is " & _
CStr(Cache("Age")) & " years old."
End Sub

Notes


Like the Application object, the Cache object is more commonly
accessed directly through the Cache property, rather than by
obtaining a local object reference to the Cache instance for the
application.

Chapter 13 discusses when you might use the
ASP.NET Cache rather than the Application state collection, and
vice-versa.

The Cache class includes the members shown in
Table 12-2.

Table 12-3. Cache class members

Cache member


Description


Add method


Adds an item to the cache


Count property


Indicates the number of items contained in the cache


Get method


Returns an object representing data in the cache with a particular
key value


Insert method


Inserts an item into the cache and assigns it a key


Item property


Returns an object representing a cache item based on its key value or
sets an item of data in the cache while assigning it a key value


Remove method


Removes an item with a particular key value from the cache

ClientTarget

String = Page.ClientTarget

Gets or sets a string value that allows you to
override automatic browser detection in ASP.NET, force the page to be
rendered for a browser type configured in

machine.config or

web.config , and specified by this property. The
available preconfigured values for this property are as follows:

downlevel



The page will be rendered based on the browser capabilities defined
for unknown browsers in the <browserCaps>
element of

machine.config .


ie4



The page will be rendered based on the values for Internet Explorer
4.0 configured in the <browserCaps> element
of

machine.config .


ie5



The page will be rendered based on the values for Internet Explorer
5.0 configured in the <browserCaps> element
of

machine.config .



Parameter


String



A string that specifies the alias for the browser capabilities that
the page will target.



Example


The following code example initializes the ClientTarget property of
the Page class to downlevel,
indicating that ASP.NET must render the page for an unknown browser
type, which will result in HTML 3.2-compliant output. The example
then displays a message indicating whether a set of features is
supported. In the case of downlevel, none of the
listed features is supported.

Sub Page_Load( )
Page.ClientTarget = "downlevel"
Message.Text = "Page is set to render for the " & _
Page.ClientTarget & " alias.<br/>"
Message.Text &= "Supported features:<br/>"
Message.Text &= " - JavaScript: " & _
Request.Browser.JavaScript & "<br/>"
Message.Text &= " - ActiveX Controls: " & _
Request.Browser.ActiveXControls & "<br/>"
Message.Text &= " - Frames: " & _
Request.Browser.Frames & "<br/>"
End Sub

Notes


The ClientTarget can also be specified by using the
ClientTarget attribute of the @
Page directive.

Changing the value of the ClientTarget property in the example to
ie4 will result in output indicating that all of
the listed features are supported.

While most server controls render HTML 3.2 for all browsers, the
validation controls are an example of controls that render
differently, depending on the value of ClientTarget. If the
ClientTarget property is set to downlevel, then
validation is performed on the server side, meaning that if we view
the source, no client-side script will perform the validation.

If the ClientTarget is set to uplevel, then the
validation controls emit client-side JavaScript to perform
client-side validation.

Context

HttpContext = Page.Context

Returns an HttpContext instance containing
context information for the current HTTP request.

Parameter


HttpContext



A variable of type HttpContext that will receive the reference to the
current HttpContext instance.



Example


The following code example uses the Context property to return the
name of the currently logged in user. This information is also
available from the User property of the Page
class, which is derived from the HttpContext associated with the
current request.

Sub Page_Load( )
Message.Text = "Currently logged in as: " & _
Context.User.Identity.Name
End Sub

Notes


A common use of this property is to pass a reference to the
HttpContext for the current request to a business object that needs
access to the ASP.NET intrinsic objects (Request, Response, etc.). In
addition to providing access to the Application, Request, Response,
Server, and Session intrinsics, the HttpContext
class provides access to the Trace and User information for the
current HTTP request.

EnableViewState

Boolean = Page.EnableViewState
Page.EnableViewState = Boolean

Returns or sets a Boolean value that indicates
whether the Page maintains its view state and that of server controls
it contains. The default value of this property is
True, which means that the page maintains its view
state.

Parameter


Boolean



A Boolean value that indicates whether the page maintains its view
state.



Example


The following code example sets EnableViewState to
False using the EnableViewState
attribute of the @ Page
directive and displays its value on the page:

<%@ Page Language="vb" EnableViewState="True" %>
<html>
<head>
<title></title>
<script runat="server">
Sub Page_Load( )
If Page.EnableViewState = True Then
Message.Text = "ViewState is enabled."
Else
Message.Text = "ViewState is disabled."
End If
End Sub
</script>
</head>
<body>
<form runat="server">
<asp:label id="Message" runat="server"/>
</form>
</body>
</html>

Notes


The EnableViewState property can also be specified using the
EnableViewState attribute of the
@ Page directive, as shown in
the example.

Examining a page's HTML source using a
browser's View Source feature shows the effect of
the EnableViewState property. If the EnableViewState property is set
to False, the source will look similar to:

<input type="hidden" name="_  _VIEWSTATE" 
value="dDwxMDA3MzE2MzEyOzs+" />

If the EnableViewState property is set to True,
the source will look similar to:

<input type="hidden" name="_  _VIEWSTATE" 
value="dDwxMDA3MzE2MzEyO3Q8O2w8aTwxPjs+O2w8dDw7bDxpPDM+Oz47bDx0PHA8cDxsPF
RleHQ7PjtsPFZhbHVlIG9mIHRoZSBFbmFibGVWaWV3U3RhdGUgcHJvcGVydHkgaXMgVHJ1ZTs
+Pjs+Ozs+Oz4+Oz4+Oz4=" />

The extra characters in the value of the _
_VIEWSTATE
hidden field indicate the view state of the
current page. The view state of a page includes the transient
properties of server controls, such as BackColor or ForeColor.

Note that pages that do not contain a <form>
element with the runat="server" attribute will not
save view state, regardless of the value of the EnableViewState
property.

ErrorPage

String = Page.ErrorPage
Page.ErrorPage = String

Returns or sets
the name of the page to redirect to in the event of an unhandled page
exception.

Parameter


String



A String value that indicates the name of the page to redirect to in
the event of an unhandled page exception.



Example


The next example changes the ErrorPage property and shows the
executed page when an unhandled exception occurs in the page:

Sub Page_Load( )
Page.ErrorPage = "ErrorPage_Handler.aspx"
Dim x, y, overflow As Integer
x = 1
y = 0
overflow = x/y
'This code will not be executed
Message.Text = "Error Page is " & Page.ErrorPage & "."
End Sub

The Page_Load for

ErrorPage_Handler.aspx follows:

Sub Page_Load( )
Message.Text = "We're sorry. An error occurred during the" & _
" processing of your request. Please try again later."
End Sub

Notes


The ErrorPage property can also be specified using the
ErrorPage attribute of the @
Page directive.

IsPostBack

Boolean = Page.IsPostBack

Returns a Boolean
value that indicates if the page is loaded for the first time
(False) or is loaded as a result of the client
postback (True). This property comes in handy for
the logic that needs to be executed the first time the page is
executed or every time the page is posted back to itself, depending
on how you structure your If statement.

Parameter


Boolean



A Boolean value that indicates if the page is loaded for the first
time or is loaded as a result of the client postback.



Example


The next code example uses the IsPostBack property to display
different messages in the Label control, depending on whether the
page is loaded for the first time or is loaded as a result of the
client postback. The first time the page is loaded, the IsPostBack
property returns False, causing the string
"Non-PostBack" to be displayed.
Clicking the button posts the page back to itself, causing IsPostBack
to return True and the string
"PostBack" to be displayed.

<%@ Page Language="vb" %>
<html>
<head>
<title></title>
<script runat="server">
Sub Page_Load( )
If Page.IsPostBack Then
Message.Text = "PostBack"
Else
Message.Text = "Non-PostBack"
End If
End Sub
</script>
</head>
<body>
<form runat="server">
<asp:button id="post" Text="Post page" runat="server"/>
<asp:label id="Message" runat="server"/>
</form>
</body>
</html>

Notes


The IsPostBack property will return True only for
pages that contain a <form> element with the
runat="server" attribute and at least one control
that causes a postback. This can be a Button control, as shown in the
example, or another control, such as a DropDownList control, whose
AutoPostBack property is set to
True.

IsValid

Boolean = Page.IsValid

Returns a Boolean value, indicating whether
any validation controls on the page were unable to successfully
validate user input.

Parameter


Boolean



A Boolean indicating whether the validation succeeded.



Example


The example uses the IsValid property to determine whether validation
on the current page succeeded, and displays a message:

<%@ Page Language="vb" %>
<html>
<head>
<title></title>
<script runat="server">
Sub Page_Load( )
If IsPostBack Then
Page.Validate( )
If Page.IsValid Then
Message.Text = "Page is valid."
Else
Message.Text = "Page is not valid."
End If
End If
End Sub
</script>
</head>
<body>
<form runat="server">
Enter your name:
<asp:textbox id="name" runat="server"/>
<asp:requiredfieldvalidator
id="rfvName"
controltovalidate="name"
enableclientscript="false"
errormessage="Required!"
runat="server"/>
<br/>
<asp:button id="submit" Text="Submit" runat="server"/>
<br/>
<asp:label id="Message" runat="server"/>
</form>
</body>
</html>

Notes


The IsValid property determines whether the overall validation
performed by a form's validator controls has
succeeded. If the page has no validator controls, the
property's value is always True.
Before checking the value of IsValid, you must either call the
Page.Validate method, as shown in the example, or have submitted the
page with a control (such as a Button, ImageButton, or LinkButton
control) whose CausesValidation property is set to
True. Otherwise, an exception will occur.

In the example, the EnableClientScript property of
the RequiredFieldValidator control is set to
False, which disables client-side validation. By
default, client-side validation is enabled and the page is never
submitted to the server if the validation fails. Uplevel browsers
perform validation on the client using client-side scripts, and only
when validation succeeds is the page submitted. Only when the page is
submitted is the server-side event handler code executed and the
message displayed based on the value of the IsValid property.

Checking the IsValid property is important whether client-side
validation is enabled, since a malicious client could bypass
client-side validation

Request

HttpRequest = Page.Request

Returns an instance of the
HttpRequest class that
allows us to access data from the incoming HTTP requests.
It's the equivalent of the ASP intrinsic Request
object. For more information on the HttpRequest
class, see Chapter 16.

Parameter


HttpRequest



An object of type HttpRequest that contains the data from the
incoming HTTP requests.



Example


The following code example uses the ServerVariables collection of the
HttpRequest object to display the IP address of the client making the
request:

Sub Page_Load( )
Message.Text = "The current request is from: " & _
CStr(Request.ServerVariables.Item("REMOTE_ADDRESS"))
End Sub

Notes


As with the Application and Cache properties, while you can retrieve
a local reference to the HttpRequest instance associated with the
request, it is more common to access this instance directly through
the Request property, as shown in this example.

Response

HttpResponse = Page.Response

Returns an instance of the
HttpResponse class that
stores information about the response and allows us to send HTTP
response data to a browser. It's the equivalent of
the ASP intrinsic Response object. For information on the
HttpResponse class, see Chapter 17.

Parameter


HttpResponse



An object of type HttpResponse that receives the instance of the
HttpResponse class.



Example


The following example uses the Response property of the page object
to set the ContentType property of the
HttpResponse class to text/xml.
Setting this property will result in the output of the page being
displayed as XML markup in Internet Explorer 5.0 or above.

Sub Page_Load( )
Response.ContentType = "text/xml"
Message.Text = "This page will be displayed as XML in " & _
"Internet Explorer 5.0 or above."
End Sub

Notes


As with the Application and Cache properties, while you can retrieve
a local reference to the HttpResponse instance associated with the
request, it is more common to access this instance directly through
the Request property, as shown in this example.

Server

HttpServerUtility = Page.Server

Returns an instance of the
HttpServerUtility
class, which exposes useful methods for working with ASP.NET
requests. For more information on the
HttpServerUtility class, see Chapter 18.

Parameter


HttpServerUtility



An object of type HttpServerUtility that may be used to access useful
properties and methods exposed by this class.



Example


The following code example uses the Server property to access the
HtmlEncode method of the HttpServerUtility class,
which allows you to encode HTML tags and characters so that they will
be displayed to the user, rather than interpreted and rendered by the
browser:

Sub Page_Load( )
Message.Text = Server.HtmlEncode("<em>Hello, World!</em>")
End Sub

The HTML rendered from this page would look like the following:

<html>
<head>
<title>Server property example</title>
</head>
<body>
<span id="Message">&lt;em&gt;Hello, World!&lt;/em&gt;</span>
</body>
</html>

Notes


As with the Request and Response properties, while you can retrieve a
local reference to the HttpServerUtility instance associated with the
application, it is more common to access this instance directly
through the Server property, as shown in this example.

Session

HttpSessionState = Page.Session

Returns an object that represents the
current user session. A Session object is maintained for each user
that requests a page from an ASP.NET application. You can store
session-specific data in the Session object and then access it across
multiple pages in an ASP.NET application. For more information on the
HttpSessionState class, see Chapter 19.

Parameter


HttpSessionState



An HttpSessionState object that represents the current user session.



Example


The example uses the Session object to display the value of the Mode
property, which indicates where session state information is stored:

Sub Page_Load( )
Message.Text = "Current Session State Mode: " &_
Session.Mode.ToString( )
End Sub

Notes


As with the Request and Response properties, while you can retrieve a
local reference to the HttpSessionState instance associated with the
request, it is more common to access this instance directly through
the Session property, as shown in this example.

SmartNavigation

Boolean = Page.SmartNavigation
Page.SmartNavigation = Boolean

Returns or sets a Boolean indicating whether
the SmartNavigation feature is turned on. The SmartNavigation
feature, which is compatible only with Internet Explorer, uses
<iframe> elements to allow only portions of
the page to be refreshed when the page is posted back. This can help
eliminate the annoying visual flicker associated with postbacks.

Parameter


Boolean



A Boolean value that indicates whether or not SmartNavigation is
enabled.



Example


The following code example sets the SmartNavigation property to
True using the SmartNavigation
attribute of the @ Page
directive. When the page is posted back, only the current page will
be stored in the browser's history, so the Back
button will be disabled.

<%@ Page Language="vb" SmartNavigation="True" %>
<html>
<head>
<title>SmartNavigation property example</title>
<script runat="server">
Sub Page_Load( )
Message.Text = "This Label will change."
Message2.Text = "This Label will not change."
End Sub
Sub UpdateLabel(Sender As Object, e As EventArgs)
Message.Text = "This Label has changed."
End Sub
</script>
</head>
<body>
<form runat="server">
<asp:label id="Message" runat="server"/>
<asp:button id="update"
onClick="UpdateLabel"
text="Click to update label text"
runat="server"/>
</form>
<asp:label id="Message2" runat="server"/>
</body>
</html>

Notes


In addition to eliminating flicker when navigating or posting back,
SmartNavigation maintains the current scroll position when a page is
posted back and maintains only a single page in the
browser's history, which prevents users from
clicking the browser's Back button to go to a
previous state of the page.

While you can set this property from code, it is recommended that
this property be set using the SmartNavigation
attribute of the @ Page
directive, as shown in this example.

Trace

TraceContext = Page.Trace

Returns the
TraceContext object for the current web request.
Tracing provides the details about the execution of the web request.
The TraceContext class
includes the members shown in Table 12-3.

Table 12-4. TraceContext class members

Member


Description


IsEnabled


Indicates whether tracing is enabled for the current page.


TraceMode


A member of the TraceMode enumeration that indicates how items should
be sorted. Possible values are SortByCategory and
SortByTime. The latter is the default value
defined in

machine.config .


Warn method


Writes a message to the trace log using red text.


Write method


Writes a message to the trace log.

Parameter


TraceContext



An instance of the TraceContext class.



Example


The example turns tracing on programmatically by using the Trace
property of the Page class:

Sub Page_Load( )
If Trace.IsEnabled = True Then
Message.Text = "Tracing is enabled."
Else
Message.Text = "Tracing is not enabled."
End If
End Sub

Notes


As with the Request and Response properties, while you can retrieve a
local reference to the TraceContext instance associated with the
request, it is more common to access this instance directly through
the Trace property, as shown in the preceding example. For more
information on application tracing, see Chapter 10.

User

IPrincipal = Page.User

Returns an instance of an object implementing
the
IPrincipal interface containing security
information about the user making the page request. The
IPrincipal interface implements the members shown
in Table 12-4.

Table 12-5. Iprincipal interface members

Member


Description


Identity
property


Returns the Identity object representing the user requesting the page


IsInRole
property


Indicates whether the user requesting the page is in a particular role

Parameter


IPrincipal



An object variable that implements IPrincipal.



Example


The example obtains the user's authentication status
and name using the User property and displays it in the browser:

Sub Page_Load( )
Message.Text = "Authenticated: " & _
User.Identity.IsAuthenticated & "<br/>"
Message.Text &= "User Name: " & User.Identity.Name
End Sub

Notes


For the IPrincipal object returned by the User property to be
populated, some form of authentication must be configured in either

machine.config or

web.config , and, at a minimum, an authorization
rule must be configured that excludes anonymous users. If these
conditions are not met, the IsAuthenticated property of the IIdentity
object will return False and the Name property
will return an empty string.

ViewState

StateBag = Page.ViewState

The ViewState property returns an instance of the
StateBag class
containing state information for server controls on the page. This
StateBag instance can also store arbitrary data that needs to be
preserved across multiple requests for the same page.

Parameter


StateBag



An object of type StateBag that contains the property values for
server controls on the page. This StateBag instance can also store
arbitrary data that needs to be preserved across multiple requests
for the same page.



Example


The following code example sets the ForeColor property of the Message
control, and then stores the value of that color in the ViewState
StateBag instance. If the page is posted back, the code retrieves the
color that was stored, and depending on the name of the color,
changes the color from Red to
Black, or vice-versa.

<%@ Page Language="vb" %>
<html>
<head>
<title>ViewState property example</title>
<script runat="server">
Sub Page_Load( )
Dim LocalColor As System.Drawing.Color
If IsPostBack Then
LocalColor = CType(ViewState("LabelColor"), _
System.Drawing.Color)
If LocalColor.Name = "Black" Then
LocalColor = System.Drawing.Color.Red
Else
LocalColor = System.Drawing.Color.Black
End If
Message.ForeColor = LocalColor
Message.Text = "Label color is " & LocalColor.Name
ViewState("LabelColor") = LocalColor
Else
Message.ForeColor = System.Drawing.Color.Black
LocalColor = Message.ForeColor
Message.Text = "Label color is " & LocalColor.Name
ViewState("LabelColor") = LocalColor
End If
End Sub
</script>
</head>
<body>
<form runat="server">
<asp:button id="button"
text="Click to change label color"
runat="server"/>
<asp:label id="Message" runat="server"/>
</form>
</body>
</html>

Notes


ViewState, in addition to managing state for server controls
automatically, is a convenient place for ambient page state that
needs to be maintained from request to request. In addition to
storing primitive data types such as integers and strings, the
StateBag class can be used to store objects, as
long as those objects support serialization, as does the Color
structure in the example. When you store an object that supports
serialization in ViewState, the object's state is
automatically serialized into a form that can be stored in ViewState
and deserialized into an object instance when you reference the
object again.

Because ViewState does not store type information with the object,
you must cast the object retrieved from ViewState to the correct
type. In the case of the example, this type is System.Drawing.Color.

Finally, think carefully before storing large objects (such as
datasets) in ViewState. Because ViewState is stored as a hidden form
field, it is sent to the browser with each request. Storing large
objects in ViewState will result in slower page load times.

ViewStateUserKey

String = Page.ViewStateUserKey
Page.ViewStateUserKey = String

The ViewStateUserKey
property sets or returns a string representing a unique identifier
for the ViewState for a given request. This property, which must be
set in the Page_Init event handler, prevents 1-click attacks (in
which a user is induced to click on a link or to take some other
action while logged into a site, which would result in their account
being used to purchase goods for another person or account) by
assigning a unique identifier, such as the user's
Session ID to the property. When the request is processed, this value
is included in the machine authentication check performed on the
ViewState, so if a different value is found during the machine
authentication check on postback, an exception is thrown.

Parameter


String



A String containing a unique identifier for the current user.



Example


The following code example sets the
ViewStateUserKey property of the Message control
to the SessionID of the current user's session. This
value is then integrated into the ViewState machine authentication
check. If the page is posted back from a user or page with a
different SessionID, the machine authentication check will fail, and
an exception will be raised.

<%@ Page Language="vb" %>
<html>
<head>
<title>ViewStateUserKey property example</title>
<script runat="server">
Sub Page_Init( )
Page.ViewStateUserKey = Session.SessionID( )
End Sub
</script>
</head>
<body>
<form id="Form1" method="post" runat="server">
<table id="Table1" cellSpacing="1" cellPadding="1" width="100%" border="1" runat="server">
<tr>
<td>
<asp:Label id="Label1"
runat="server">First Name:</asp:Label></td>
<td>
<asp:TextBox id="FirstName"
runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>
<asp:Label id="Label2"
runat="server">Last Name:</asp:Label></td>
<td>
<asp:TextBox id="LastName"
runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>
<asp:Button id="Submit"
runat="server" Text="Submit"></asp:Button></td>
<td><input type="reset" value="Reset" runat="server"></td>
</tr>
</table>
</form>
</body>
</html>

Notes


For the ViewStateUserKey field to be effective, the
EnableViewStateMac property for the page must be set to
True, which is the default.


/ 873