Microsoft.NET

……………………………………………….Expertise in .NET Technologies

ASP.NET 2.0 Page Model – Part I

Posted by Ravi Varma Thumati on October 5, 2009

In ASP.NET 1.x, developers had a choice between an inline code model and a code-behind code model. Code-behind could be implemented using either the Src attribute or the CodeBehind attribute of the @Page directive. In ASP.NET 2.0, developers still have a choice between inline code and code-behind, but there have been significant enhancements to the code-behind model.

Improvements in the Code-Behind Model

In order to fully understand the changes in the code-behind model in ASP.NET 2.0, its best to quickly review the model as it existed in ASP.NET 1.x.

The Code-Behind Model in ASP.NET 1.x

In ASP.NET 1.x, the code-behind model consisted of an ASPX file (the Webform) and a code-behind file containing programming code. The two files were connected using the @Page directive in the ASPX file. Each control on the ASPX page had a corresponding declaration in the code-behind file as an instance variable. The code-behind file also contained code for event binding and generated code necessary for the Visual Studio designer. This model worked fairly well, but because every ASP.NET element in the ASPX page required corresponding code in the code-behind file, there was no true separation of code and content. For example, if a designer added a new server control to an ASPX file outside of the Visual Studio IDE, the application would break due to the absence of a declaration for that control in the code-behind file.

The Code-Behind Model in ASP.NET 2.0

ASP.NET 2.0 greatly improves upon this model. In ASP.NET 2.0, code-behind is implemented using the new partial classes provided in ASP.NET 2.0. The code-behind class in ASP.NET 2.0 is defined as a partial class meaning that it contains only part of the class definition. The remaining part of the class definition is dynamically generated by ASP.NET 2.0 using the ASPX page at runtime or when the Web site is precompiled. The link between the code-behind file and the ASPX page is still established using the @ Page directive. However, instead of a CodeBehind or Src attribute, ASP.NET 2.0 now uses the CodeFile attribute. The Inherits attribute is also used to specify the class name for the page.

A typical @ Page directive might look like this:

<%@Page AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

A typical class definition in an ASP.NET 2.0 code-behind file might look like this:

public partial class _Default : System.Web.UI.Page

Note: C# and Visual Basic are the only managed languages that currently support partial classes. Therefore, developers using J# will not be able to use the code-behind model in ASP.NET 2.0.

The new model enhances the code-behind model because developers will now have code files that contain only the code that they have created. It also provides for a true separation of code and content because there are no instance variable declarations in the code-behind file.

Note: Because the partial class for the ASPX page is where event binding takes place, Visual Basic developers can realize a slight performance increase by using the Handles keyword in code-behind to bind events. C# has no equivalent keyword.

New @ Page Directive Attributes

ASP.NET 2.0 adds many new attributes to the @ Page directive. The following attributes are new in ASP.NET 2.0.

Async

The Async attribute allows you to configure page to be executed asynchronously. Well cover asynchronous pages later in this module.

AsyncTimeout

Specified the timeout for asynchronous pages, the default is 45 seconds.

CodeFile

The CodeFile attribute is the replacement for the CodeBehind attribute in Visual Studio 2002/2003.

CodeFileBaseClass

The CodeFileBaseClass attribute is used in cases where you want multiple pages to derive from a single base class. Because of the implementation of partial classes in ASP.NET, without this attribute, a base class that uses shared common fields to reference controls declared in an ASPX page would not work properly because ASP.NETs compilation engine will automatically create new members based on controls in the page. Therefore, if you want a common base class for two or more pages in ASP.NET, you will need to define specify your base class in the CodeFileBaseClass attribute and then derive each pages class from that base class. The CodeFile attribute is also required when this attribute is used.

CompilationMode

This attribute allows you to set the CompilationMode property of the ASPX page. The CompilationMode property is an enumeration containing the values Always, Auto, and Never. The default is Always. The Auto setting will prevent ASP.NET from dynamically compiling the page if possible. Excluding pages from dynamic compilation increases performance. However, if a page that is excluded contains that code that must be compiled, an error will be thrown when the page is browsed.

EnableEventValidation

This attribute specifies whether or not postback and callback events are validated. When this is enabled, arguments to postback or callback events are checked to ensure that they originated from the server control that originally rendered them.

EnableTheming

This attribute specifies whether or not ASP.NET themes are used on a page. The default is false.

LinePragmas

This attribute specifies whether line pragmas should be added during compilation. Line pragmas are options used by debuggers to mark specific sections of code.

MaintainScrollPositionOnPostback

This attribute specifies whether or not JavaScript is injected into the page in order to maintain scroll position between postbacks. This attribute is false by default.

When this attribute is true, ASP.NET will add a <script> block on postback that looks like this:

<script src="/website/WebResource.axd?d=jBAvpwrdOM_V_Xzeox989A2 &t=632653133849531250"> </script>

Note that the src for this script block is WebResource.axd. This resource is not a physical path. When this script is requested, ASP.NET dynamically builds the script.

MasterPageFile

This attribute specifies the master page file for the current page. The path can be relative or absolute.

StyleSheetTheme

This attribute allows you to override user-interface appearance properties defined by an ASP.NET 2.0 theme.

Theme

Specifies the theme for the page. If a value is not specified for the StyleSheetTheme attribute, the Theme attribute overrides all styles applied to controls on the page.

Title

Sets the title for the page. The value specified here will appear in the <title> element of the rendered page.

ViewStateEncryptionMode

Sets the value for the ViewStateEncryptionMode enumeration. The available values are Always, Auto, and Never. The default value is Auto. When this attribute is set to a value of Auto, viewstate is encrypted is a control requests it by calling the RegisterRequiresViewStateEncryption method.

Setting Public Property Values via the @ Page Directive

Another new capability of the @ Page directive in ASP.NET 2.0 is the ability to set the initial value of public properties of a base class. Suppose, for example, that you have a public property called SomeText in your base class and you’d like it to be initialized to Hello when a page is loaded. You can accomplish this by simply setting the value in the @ Page directive like so:

<%@Page SomeText="Hello!" Inherits="PageBase" %>

The SomeText attribute of the @ Page directive sets the initial value of the SomeText property in the base class to Hello!

New Public Properties of the Page Class

The following public properties are new in ASP.NET 2.0.

AppRelativeTemplateSourceDirectory

Returns the application-relative path to the page or control. For example, for a page located at http://app/folder/page.aspx, the property returns ~/folder/.

AppRelativeVirtualPath

Returns the relative virtual directory path to the page or control. For example for a page located at http://app/folder/page.aspx, the property returns ~/folder/page.aspx.

AsyncTimeout

Gets or sets the timeout used for asynchronous page handling. (Asynchronous pages will be covered later in this module.)

ClientQueryString

A read-only property that returns the query string portion of the requested URL. This value is URL encoded. You can use the UrlDecode method of the HttpServerUtility class to decode it.

ClientScript

This property returns a ClientScriptManager object that can be used to manage ASP.NETs emission of client-side script. (The ClientScriptManager class is covered later in this module.)

EnableEventValidation

This property controls whether or not event validation is enabled for postback and callback events. When enabled, arguments to postback or callback events are verified to ensure that they originated from the server control that originally rendered them.

EnableTheming

This property gets or sets a Boolean that specifies whether or not an ASP.NET 2.0 theme applies to the page.

Form

This property returns the HTML form on the ASPX page as an HtmlForm object.

Header

This property returns a reference to an HtmlHead object that contains the page header. You can use the returned HtmlHead object to get/set style sheets, Meta tags, etc.

IdSeparator

This read-only property gets the character that is used to separate control identifiers when ASP.NET is building a unique ID for controls on a page. It is not intended to be used directly from your code.

IsAsync

This property allows for asynchronous pages. Asynchronous pages are discussed later in this module.

IsCallback

This read-only property returns true if the page is the result of a call back. Call backs are discussed later in this module.

IsCrossPagePostBack

This read-only property returns true if the page is part of a cross-page postback. Cross-page postbacks are covered later in this module.

Items

Returns a reference to an IDictionary instance that contains all objects stored in the pages context. You can add items to this IDictionary object and they will be available to you throughout the lifetime of the context.

MaintainScrollPositionOnPostBack

This property controls whether or not ASP.NET emits JavaScript that maintains the pages scroll position in the browser after a postback occurs. (Details of this property were discussed earlier in this module.)

Master

This read-only property returns a reference to the MasterPage instance for a page to which a master page has been applied.

MasterPageFile

Gets or sets the master page filename for the page. This property can only be set in the PreInit method.

MaxPageStateFieldLength

This property gets or sets the maximum length for the pages state in bytes. If the property is set to a positive number, the pages view state will be broken up into multiple hidden fields so that it doesnt exceed the number of bytes specified. If the property is a negative number, the view state will not be broken into chunks.

PageAdapter

Returns a reference to the PageAdapter object that modifies the page for the requesting browser.

PreviousPage

Returns a reference to the previous page in cases of a Server.Transfer or a cross-page postback.

SkinID

Specifies the ASP.NET 2.0 skin to apply to the page.

StyleSheetTheme

This property gets or sets the style sheet that is applied to a page.

TemplateControl

Returns a reference to the containing control for the page.

Theme

Gets or sets the name of the ASP.NET 2.0 theme applied to the page. This value must be set prior to the PreInit method.

Title

This property gets or sets the title for the page as obtained from the pages header.

ViewStateEncryptionMode

Gets or sets the ViewStateEncryptionMode of the page. See a detailed discussion of this property earlier in this module.

New Protected Properties of the Page Class

The following are the new protected properties of the Page class in ASP.NET 2.0.

Adapter

Returns a reference to the ControlAdapter that renders the page on the device that requested it.

AsyncMode

This property indicates whether or not the page is processed asynchronously. It is intended for use by the runtime and not directly in code.

ClientIDSeparator

This property returns the character used as a separator when creating unique client IDs for controls. It is intended for use by the runtime and not directly in code.

PageStatePersister

This property returns the PageStatePersister object for the page. This property is primarily used by ASP.NET control developers.

UniqueFilePathSuffix

This property returns a unique suffic that is appended to the file path for caching browsers. The default value is __ufps= and a 6-digit number.

New Public Methods for the Page Class

The following public methods are new to the Page class in ASP.NET 2.0.

AddOnPreRenderCompleteAsync

This method registers event handler delegates for asynchronous page execution. Asynchronous pages are discussed later in this module.

ApplyStyleSheetSkin

Applies the properties in a pages style sheet to the page.

ExecuteRegisteredAsyncTasks

This method beings an asynchronous task.

GetValidators

Returns a collection of validators for the specified validation group or the default validation group if none is specified.

RegisterAsyncTask

This method registers a new async task. Asynchronous pages are covered later in this module.

RegisterRequiresControlState

This method tells ASP.NET that the pages control state must be persisted.

RegisterRequiresViewStateEncryption

This method tells ASP.NET that the pages viewstate requires encryption.

ResolveClientUrl

Returns a relative URL that can be used for client requests for images, etc.

SetFocus

This method will set the focus to the control that is specified when the page is initially loaded.

UnregisterRequiresControlState

This method will unregister the control that is passed to it as no longer requiring control state persistence.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: