Active Server Pages

   

This is not your daddy 's ASP. Control-based encapsulation, clean separation of code from HTML, strongly typed languages, compiled languages, and event-based page processing will radically change the way you develop user interface (UI) for server-based Web applications. This section introduces the ASP.NET page framework from the ground up. It covers ASP.NET syntax, page directives, page processing, control processing, and postback, and offers a comprehensive look at controls: control families, intrinsic controls, list controls, rich controls, and mobile controls. Finally, it examines declarative user controls, which are the essential starting points for any developer who wants to create Web UI using ASP.NET.

ASP.NET provides a very simple model for programming when seen from a high level. Figure 1.5 shows how ASP.NET fits into the big picture.

Figure 1.5. ASP.NET simplifies the application development model.

graphics/01fig05.gif

Many of you have developed ASP applications in which the files all have .asp extensions. ASP.NET application files have an .aspx extension to differentiate them from ASP files. Because of the difference in extensions, both classic ASP and ASP.NET can function side by side in the same Web site.

ASP.NET files have a major performance advantage over ASP files. The first time they are requested , they are compiled into native code. This way, they execute much faster than the interpreted ASP files.

In classic ASP, you didn't have many language choices. Anything you could do in HTML, such as JScript and JavaScript, was available. For server-side programming, JScript and VBScript were the only choices (of course, any scripting language implemented according to Microsoft's scripting profile could be used, but this was a lot of trouble). Now with ASP.NET, you get VB, C#, and JScript out of the box. Other languages, such as Cobol, RPG, Pascal, and many others are under development by third-party vendors . ASP.NET was developed from the ground up to be language agnostic ”any language should give you similar final results. The three out-of-the-box languages are covered in detail in Chapter 2, "ASP.NET Languages."

These features ”multiple language support and runtime compilation to native code ”don't require developers to put forth any extra effort. To save an ASP.NET file, all you have to do is save it to disk ”you don't need to use a compile button or any take any other steps.

ASP.NET has a new control-based, event-driven execution model. You can hook a Page_Load() method, an event a server-side control fires off such as an OnItemCommand() method, or any other event that is available. This is covered in detail in Chapter 6, "ASP.NET Controls."

In all, the new model that ASP.NET follows requires you to write less code, it encapsulates functionality into easy-to-use classes, and reduces the amount of spaghetti code that you'll be inclined to write.

ASP.NET Page Basics

To start with, the simplest ASP.NET page can be as simple as an HTML file that's renamed with an .aspx extension. It can, however, contain much more than static HTML. The following list shows you the elements that can be found in an ASP.NET page:

  • Directives. <%@ Directive %>

  • Server controls. <tag runat =server>

  • Code blocks. <script runat=server>

  • Data bind expressions. <%# %>

  • Server-side comments. <%-- --%>

  • Render code. <%= %> and <% %>

The following is a simple ASP.NET page. You can see the directive at the top that determines the language (VB) and several other attributes. You also can see an ASP.NET server control in the <asp:Label> tag. The <% and %> tags designate an area in which the developer can add some code. The remainder of the file is plain HTML.

 <%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.vb" graphics/ccc.gif Inherits="WebApplication4.WebForm1"%>  <html><head>    <body>      <form id="WebForm1" method="post" runat="server">  <asp:Label id=Label1 runat="server">This is some label text.</asp:Label>      </form>  <%     ' Do some code here.  %>  </body></html> 

Server Control Syntax

Server controls are declared as HTML or XML tags with a runat=server attribute. The following two examples show a TextBox and a Calendar control:

 <asp:TextBox id=TextBox1 runat="server">Some text here</asp:TextBox>  <asp:calendar id=Calendar1 runat="server" /> 

The tag identifies which control to create. The controls are implemented as .NET classes. ID attributes provide a programmatic accessor.

Tag attributes map to control properties. The following two examples show ID tags set differently, and a Text and Height attribute is set for each respective control:

 <asp:MyControl id="t1" Text="Foo" runat="server" />  <asp:YourControl id="t2" Height="5" runat="server" /> 

Control properties can be set programmatically as follows:

 t1.Text = "Bar"  t2.Height = 99 

Tags and attributes are not case sensitive.

Input controls can automatically populate their object models from values entered on the client. No "glue" code is required to restore values to inputs. There is no state stored on the server, and best of all, and the state persistence works with all browsers!

Code Basics

Server code lives in a script block marked runat="server" as the following three examples show:

 <script language="VB" runat=server>    ' Do some VB code here...  </script>  <script language="C#" runat=server>    // Do some C# code here...  </script>  <script language="JScript" runat=server>    // Do some JScript code here...  </script> 

The code blocks can contain variables , methods , and event handlers.

You can use events to structure pages. Doing so results in clean code organization and avoids the "Monster If " statement. The code can synchronize Page events, such as Page_Load() and Page_Unload() . The code can synchronize control events, such as Button1_Click() and Textbox1_Changed() .

ASP.NET Page Life Cycle

The first thing that's executed is the Page_Load() method. It fires at the beginning of a request after controls are initialized . By this time, all input controls values are already populated , as the following example shows:

 Sub Page_Load      message.Text = textbox1.Text  End Sub 

Page_Load fires on every request for an ASP.NET page. You can use Page.IsPostBack to execute conditional logic, as in the following example:

 Sub Page_Load(s As Object,e As EventArgs)    If Not Page.IsPostBack Then      'executes only on initial page load      Message.Text = "initial value"    End If    ' Rest of procedure executes on every request  End Sub 

Server control events include change events, and execute only on the next request to server. Some sample events are Textbox1_Changed and CheckBox1_CheckChanged . Action events, on the other hand, cause an immediate postback to the server. An example of an action event is Button1_Click . These events work with any browser and require no client script, ActiveX controls, or applets.

Control event handlers are identified on the tag, as the following examples show:

 <asp:button onclick="button1_click" runat="server">  <asp:textbox onchanged="text1_changed" runat="server"> 

The event handler code might look like the following:

 Sub btn1_Click(s as Object.e as EventArgs)      Message.Text = "Button1 clicked"  End Sub 

The Page_Unload() method fires after the page is rendered and is useful for logging and cleanup. The following example shows how you might use it:

 Sub Page_Unload(s As Object.e As EventArgs)      MyApp.LogPageComplete()  End Sub 

Figure 1.6 gives you an idea of what an ASP.NET page lifetime might look like.

Figure 1.6. The ASP.NET page lifetime.

graphics/01fig06.gif

Non-input controls can maintain their data across multiple postback requests . Use a client-hidden field to implement this feature. This feature can be disabled per control or entire page.

Input Validation

ASP.NET offers rich and declarative input validation. The validation controls are declared separately for each input control and are part of an extensible validation framework. The validation controls automatically detect uplevel clients and avoid round trips to the server for uplevel clients . The following example uses a validation control to ensure that the TextBox1 control's required input is enforced:

 <asp:TextBox id=TextBox1 runat="server" />  <asp:RequiredFieldValidator id="Req1" ControlToValidate="TextBox1" Text="Required Field" graphics/ccc.gif runat="server" /> 

The following list shows the supported validation controls:

  • <asp:RequiredFieldValidator>

  • <asp:RangeValidator>

  • <asp:CompareValidator>

  • <asp:RegularExpressionValidator>

  • <asp:CustomValidator>

  • <asp:ValidationSummary>

The Page.IsValid property indicates whether all validation controls on the page are valid. Take a look at the following example:

 Sub Submit_click (s A Object.e As EventArgs)    If Page.IsValid Then      Message.Text = "Page is valid!"    End If  End Sub 

Pages render more richly to uplevel clients, but work well in downlevel clients, too. Page developers can identify a target client with the following directives:

 <%@ Page ClientTarget="Uplevel" %>  <%@ Page ClientTarget="Downlevel" %>  <%@ Page ClientTarget="Auto" %> 

The Request.Browser object provides more granular control of what is rendered to a given client. It exposes specific client capabilities, as the following example shows:

 If Request.Browser.Frames = True Then       'Do something special  End If 

Web Services

Web Services follow a simple programming model: Developers write .asmx files with class methods. ASP.NET compiles the files on demand and generates discovery and documentation information automatically, and incoming HTTP messages map to Web Services methods. No special HTTP or XML knowledge is required. Web Services are covered in detail in Chapter 14.

Improved ASP.NET Page Development

ASP.NET now is part declarative and part code. It combines declarative tags, such as HTML, XML, WML, and static text with code. This provides for a clean separation between code and tags.

Improved ASP.NET Deployment

ASP.NET components are dynamically updated; there are no more locked DLLs. All you need to do is copy a new DLL on top of an old one. No tools, configuration changes, application shutdowns, or reboots are required ”ASP.NET just works.

XML Configuration File

ASP.NET has a new human-readable and writable format configuration file. The configuration can be stored with the application and can be copied with the rest of a Web application. Configuration changes are automatically detected and applied to the running application. The system can store the application configuration, as well.

Security Infrastructure

ASP.NET now boasts an extensible security architecture. It has fully pluggable authentication and authorization, and can support any credential store such as a database. It comes with out-of-the-box authentication support for Basic, Digest, and NTLM.

Improved ASP.NET Availability and Performance

ASP.NET has fantastic caching support. Its goal is to reuse database queries and page processing to improve application scalability. Specifically, it comes with selective output caching, full page output caching, and an extensible cache API.

   


Special Edition Using ASP. NET
Special Edition Using ASP.Net
ISBN: 0789725606
EAN: 2147483647
Year: 2002
Pages: 233

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net