To create your first ASP.NET application, start Visual Studio .NET. At the Start Page, click the New Project button. In the New Project dialog, select either Visual Basic Project or C# Project, depending on what language you''re writing in. From the Template pane, select the ASP.NET Web Application template as shown in Figure 5.1. Change the name of the application to http://localhost/HelloWeb_vb or http://localhost/HelloWeb_cs, depending on what language you''re coding in. Click the OK button to create the application.
When you create an ASP.NET application, Visual Studio creates the virtual Web directory at the location you specify in the name of the project. In this case, the application was created at localhost, which is the default name for the local Web server running on your machine. If you want to create an application on another server, you specify the Web address and project name, and the application is created there. After the application has been created, you should see something like Figure 5.2.
You''re now in the Visual Studio .NET designer for ASP.NET applications. You''ll notice the same look and feel you saw when you were designing Windows Forms applications. The Solution Explorer displays the components of your project, the Properties window, and the Toolbox. All the windows you learned about over the last few days are available. The design environment is the same no matter what type of application you''re developing.
To understand where the files are created, navigate to the \inetpub\wwwroot\helloweb_cs or \inetpub\wwwroot\helloweb_vb directory. When you create new applications in ASP.NET, all the core application files are created directly on the Web server. This is different from writing ASP applications using Visual InterDev, which creates a local copy of files and then creates a copy on the Web server. You use the tools in Visual InterDev to release and refresh copies of files from the Web server. It''s extremely important to understand that in ASP.NET and Visual Studio .NET, the files are created directly on the Web server and there''s no local copy. Figure 5.3 shows what my directory looks like; yours should look very similar.
If you navigate to the Visual Studio Projects folder under My Documents, you''ll see a HelloWeb_vb or HelloWeb_cs directory, containing only the solution file (with the .sln extension). The solution file contains information about where the actual project files are located, so if you''re ever having trouble opening a Web project that you didn''t create, you can edit the .sln file to determine where the project files are located.
In the Solution Explorer, the files displayed in the hierarchical tree view are only the top-level files in the inheritance hierarchy for each class. That''s why more files are listed in the wwwroot directory than you see in the Solution Explorer. If you click the Show All Files button on the Solution Explorer toolbar, you can drill into the file hierarchy, as Figure 5.4 demonstrates.
The Webform1.aspx file has a Webform1.aspx.vb and Webform1.aspx.resx underneath it in the tree view. The model for Web Forms is that the ASPX files have a code-behind file, which has the same name of the ASPX file, but with the .cs or .vb extension based on the language you''re coding in. The .resx file is the resource file for the ASPX page, which can contain localization information for the Web Form.
All the server events for an ASPX page are handled in the code-behind files, whereas the user interface is contained in the ASPX file itself. Each ASPX page contains page directive attributes that set processing information on the page and indicate the inheritance hierarchy for the page. If you click the HTML button in the lower left of the Web Forms Designer, you''re switched to the HTML for the ASPX file. Notice the page directives highlighted across the top of the page, as Figure 5.5 shows.
The CodeBehind attribute contains the WebForm1.aspx.vb file, which is the class file under WebForm1.aspx in the Solution Explorer. The Inherits attribute specifies the Page class for WebForm1 to inherit. This is different from Windows Forms, where a single class file inherits a class that contains the designer information. A WebForm has a class file that''s physically separated from the designer file, which is actually the ASPX page. The ASPX page has information about what class file it should use to handle its events. The hierarchy of the files in the Solution Explorer is defined by the Page directive attributes for each file in the Solution Explorer.
If you click the Design button in the lower-left corner of the HTML designer, you''re taken back to the design surface for the ASPX page. To get to the code-behind file, you can double-click the ASPX page (as you do for a Windows Form), you can press the F7 key, or you can double-click the class file in the Solution Explorer. When you get to the code-behind class, you''ll see something like Figure 5.6.
The class file inherits the System.Web.UI.Page class. By inheriting this class for the page, all the Web-related methods, properties, and events are available to the code-behind class file.
When an ASP.NET application is compiled, the code-behind files for each ASPX page are compiled into a single assembly with a DLL extension and are placed in the Bin directory. Each time an ASPX page is called, the ASP.NET runtime on the server creates a class for the ASPX page. The created DLL uses the information in its Page directive attributes to determine where to get its events. The combination of the ASPX page''s DLL and the solution''s DLL make up the HTML that''s outputted to the end user''s Web browser.
Before we go on to the next section and begin adding controls and code to the WebForm1.aspx page, Table 5.1 lists the files that make up a solution and gives a description of what they do for you.
File Name
|
Description
|
---|---|
Webform1.aspx
|
The visual part of the Web Form. You can modify the HTML to pass the user interface of a Web form or drag controls from the Toolbox onto the Web Form.
|
WebForm1.aspx.vb or WebForm1.aspx.cs
|
Code-behind class file that the ASPX file inherits its functionality from.
|
Web.Config
|
XML-based configuration file for the project. You can set properties on security, caching, state, and tracing information in the Web.Config file.
|
Global.asax
|
Similar to the Global.asa file from ASP, the Global.asax file contains application-level events for an ASP.NET project.
|
Styles.css
|
Default style sheet for a project. You can double-click .css files to edit them in the Style Sheet Designer.
|
AssemblyInfo
|
Class file that contains assembly-specific information for the project''s assembly output.
|
.vdisco
|
Discovery file for XML Web services in the application. You learn more about discovery files on Day 13, "XML Web Service in .NET," when you learn about Web services.
|
Adding controls to a Web Form is exactly like adding controls to a Windows Form. You visually design a page by dragging predefined controls from the Toolbox onto the Web Form.
Server controls and Web controls are equivalent terms. The term server controls is more common in referring to controls that provide server-side event functionality.
When programming in ASP.NET, you have a choice of what types of controls you can use on a Web Form. There are HTML controls and server controls. HTML controls are the same HTML-tag-based controls you use in ASP or a regular HTML page. Server controls offer a richer user interface, and have an object model that you can access in the code-behind class files for an ASPX page.
To get an idea of the controls you can use, click the HTML Controls tab on the Toolbox, and then click the Web Form Controls tab on the Toolbox. Figure 5.7 gives a snapshot that comparing the different types of controls that each Toolbox tab offers.
Based on what functionality you''re trying to implement, and whether you need to write server events for a control, you can use either HTML controls or server controls. To see the different HTML that''s rendered in the designer, drag an HTML text field to the ASPX page and then drag a TextBox server control.
If you switch to the HTML view in the designer, you''ll see HTML output similar to Listing 5.1.
<body> <form id="Form1" method="post" runat="server"> <P> <asp:TextBox id="TextBox1" runat="server"></asp:TextBox></P> <P> </P> <P> <INPUT type="text"></P> </form> </body>
The HTML <Input> tag conforms to HTML version 3.2 standards. The server control, however, has an XML-like syntax to define the TextBox control and its attributes. All server controls have an <asp:controltype prefix, where controltype is the class of the control. The id attribute is the friendly name for the control, and the runat attribute denotes where the control events for the control should occur. By adding the runat=server attribute to any control, be it an HTML control or a server control, you can access the control from the inherited code-behind file. When you add the runat=server attribute, the control is declared as an object within the code-behind class file, and you can access the control object model through code within the class file.
If you switch back to the Design view of the page, and then double-click on the ASPX page, you''re taken to the code-behind file. At the top of the class file, you''ll see the following object declaration:
Protected WithEvents TextBox1 As System.Web.UI.WebControls.TextBox protected System.Web.UI.WebControls.TextBox TextBox1;
Notice that the HTML Input control isn''t declared in the code-behind file. Because the control does not have a runat=server attribute, the declaration isn''t created in the code-behind file.
Switch to the HTML view of the WebForm1.aspx page and modify the HTML Input control to look like this:
<INPUT type="text" runat="server" id="HtmlTextBox">
Then save the page and switch back to the code-behind class. You''ll notice this declaration at the top of the page along with the original TextBox1:
Protected WithEvents HtmlTextBox As System.Web.UI.HtmlControls.HtmlInputText protected System.Web.UI.HtmlControls.HtmlInputText HtmlTextBox;
When you add server controls to an ASPX page, the controls that you add are generated in the code-behind class when you save the ASPX page. If you add new items to the HTML of an ASPX page, or you drag new controls from the Toolbox onto the ASPX page, make sure that you save the page before you go to the code-behind, or you won''t see your newly added controls.
When you added the runat=server attribute to the HTML tag, you notified the ASPX page that you want to include this item in the class file, and that you want its methods, properties, and events available. Notice that the namespace for the controls is different, however. An HTML control is derived from the System.Web.UI.HtmlControls class, whereas a server control is derived from the System.Web.UI.WebControls class. Each namespace offers different properties, methods, and events based on the type of control you''re using.
Then what''s the difference, and why would you use HTML controls instead of server controls? The following bullets highlight the reasons why you would or would not choose one approach or the other:
Server controls don''t expose client events; HTML controls do. In other words, you can''t use client-side JavaScript or VBScript with a control that has a runat=server attribute.
Server controls offer a rich object model in the code-behind class that enables you to program Web applications in a way that''s similar to writing Windows applicationsby responding to events and setting properties.
If you''re migrating an ASP application to an ASP.NET application and aren''t familiar with event-driven programming, using HTML controls might seem more familiar to you.
Both sets of controls offer auto-complete and auto-list members in the HTML view, so that functionality isn''t specific to one type of control.
If you''re targeting down-level browsers such as IE 4.0 or Netscape 4.7, IIS automatically renders server controls correctly on such browsers. For example, if you''re using a drop-down list control and AbsolutePositioning on an ASPX page, the ASP.NET runtime on the server generates HTML 3.2compliant HTML that positions and HTML ComboBox inside a table. It completely changes the code you wrote so it works in the down-level browsers.
There''s overhead associated with using server controls. Because server controls must be part of the compiled assembly and processed by the ASP.NET runtime on the server, it isn''t always as efficient as using a straight HTML control.
From my experience, you use server controls when you start learning ASP.NET. You have a huge number of capabilities when designing Web-based applications using server controls, and it''s the most exciting new feature of ASP.NET. After you get the hang of server controls and HTML controls, you use both to write scalable and robust Web-based applications. Just remember that any HTML tag can have a runat=server attributea <TD> tag, an <IMG> tag, any tag. So, if you want to add functionality but need to do it server side, you can simply add the runat=server tag and handle events for the object on the server.
I mentioned that any HTML element can have a runat=server attribute. As an example, let''s say you have an HTML table, and you need to change the color of a table cell or table row, based on something that occurs in a server event. If you add the runat=server attribute to the TD HTML element and give it an ID, the code-behind class will have the following declaration:
Protected WithEvents TD1 As System.Web.UI.HtmlControls.HtmlTableCell
In your code, you can then use a Select Case statement or an If statement to set Style attributes on the HtmlTableCell object, as the following code demonstrates:
Select Case Request("AlertStatus") Case "Red" TD1.Attributes.Add("background", "red.jpg") Case "Yellow" TD1.Attributes.Add("background", "yellow.jpg") Case Else TD1.Attributes.Add("background", "green.jpg") End Select
Keep in mind that you can do anything with any HTML element in server-side code.
The benefit of using server controls is the ease with which you can write server-side code. Using the built-in functionality of the Visual Studio .NET Code Editor with auto-complete and auto-list members is certainly much easier than writing script in a text file. Just as you can handle events in a Windows Form, you can add a control to a Web Form, double-click the control, and then write code for the default event for that control. Because you''re dealing with a Web page, there are certain events that can''t occur in server-side code. To understand this better, you need to understand how server events are processed.
When a Web page is viewed in a browser, it''s just HTML. Because HTML is just a tag-based language that describes how things are supposed to look, it doesn''t support any real event processing. This can be extended by certain browsers with Dynamic HTML (or DHTML), which supports JavaScript or VBScript events for HTML elements. That means certain events can occur from a page that''s already rendered in the browser. Common events might be OnMouseOver, OnBlur, and OnClick. If a browser supports scripting, you can write script code that responds to events on the client side in the browser.
When using server controls, the event processing takes place on the server. If you write code for the Click event of a Button server control, the page is posted back to the server and the event is processed. Understanding that the event must occur on the server means that events such as OnMouseOver and OnBlur can''t occur in a server event.
Each time an event is fired for a server control, the whole page is posted back to the server. ASP.NET takes care of remembering the state of the page before and after it''s posted back to the server. You learn about how it does that with ViewState a little later.
To see how easy it is to write applications using server controls, you''ll now write a simple login form. There''s no data access yet because you don''t get into that until next week, but understanding the page events and how to work with controls are the primary foci of today.
Follow these steps to modify the WebForm1.aspx page in your Solution Explorer. Your results should look like Figure 5.9.
Make sure that you''re in the Web Forms Designer.
Delete the HTML text field control and the TextBox server control from the form.
From the main menu, select Table, Insert, Table. You are prompted with the Insert Table dialog shown in Figure 5.8.
Click the OK button to add the default table with three columns and three rows.
Drag two Label controls from the Web Forms tab of the Toolbox to the first two rows in the first column of the table. Change their Text property to User Name and Password, respectively.
Drag two TextBox controls from the Web Forms tabs of the Toolbox to the first two rows in the second column of the table. Change their Name property to UserName and Password, respectively.
Drag a Button control from the Web Forms tab to the third row on the second column in the table, and change its Text property to Log In and change its Name property to LogIn.
Your final output will look like Figure 5.9.
By default, the Web Forms Designer defaults to absolute positioning and grid layout for the designer. That means there''s a grid that you can use to line up controls similar to the Window Forms Designer, and that controls are positioned absolutely on the form. Absolute positioning sets the x and y coordinates of each control using the Style property. This sort of positioning works great in Internet Explorer, and ASP.NET converts the Style properties settings to the correct HTML for down-level browsers such as Netscape Navigator. I''m accustomed to using Table to position my HTML elements, so I set my page properties not to use the FlowLayout by right-clicking the APX page and setting its Page Layout property to GridLayout instead of FlowLayout.
Double-click on the Log In button to get to its Click event, and add the code in Listing 5.2, which writes out the contents of the TextBoxes to the form.
Private Sub LogIn_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles LogIn.Click Response.Write(UserName.Text) Response.Write("<br>") Response.Write(Password.Text) Response.End() End Sub
private void LogIn_Click(object sender, System.EventArgs e) { Response.Write(UserName.Text); Response.Write("<br>"); Response.Write(Password.Text); Response.End(); }
As when you''re writing ASP code, you can use the members of the HttpResponse class and HttpRequest class in the code-behind to read and write HTTP values sent by a browser during a Web request.
If you right-click the WebForm1.aspx page in the Solution Explorer and select Build and Browse, the page will be compiled and displayed in the internal browser of Visual Studio .NET. Your IDE should look like Figure 5.10.
Remember that ASP.NET pages are running from the compiled assembly in the Bin directory. So, if you make any changes to your code-behind files, you must rebuild the solution to make sure that you''re working with the current version of the files. If you change any of the standard HTML in the ASPX page, it isn''t compiled until the page is accessed, so you can select Save All Files from the File menu to make sure that any HTML changes have been savedyou don''t need to rebuild the project.
After the page is displayed in the browser, enter values in the UserName text box and the Password text box and click the Log In button. The results should look like Figure 5.11.
When you click the Log In button, the page is posted back to the server, and the code for the click event is processed. When you add the server controls to the form, the HTML source looks like Listing 5.3.
<TABLE id="Table1" cellSpacing="1" cellPadding="1" width="300" border="1"> <TR> <TD> <asp:Label id="Label1" runat="server">User Name:</asp:Label></TD> <TD> <asp:TextBox id="UserName" runat="server"></asp:TextBox></TD> <TD></TD> </TR> <TR> <TD> <asp:Label id="Label2" runat="server">Password:</asp:Label></TD> <TD> <asp:TextBox id="Password" runat="server"></asp:TextBox></TD> <TD></TD> </TR> <TR> <TD></TD> <TD> <asp:Button id="LogIn" runat="server" Text="Log In"> </asp:Button></TD> <TD></TD> </TR> </TABLE>
As you learned earlier, when you add server controls to a form, they use the <ASP:> tag syntax to denote that they''re server controls. The id attribute is used in the code-behind to respond to events for the control when it''s posted back to the server.
When this code is accessed by a browser, the ASP.NET runtime determines how to render the page based on the type of browser that''s accessing the page. Because no browsers understand the <ASP:> tag syntax, the ASP.NET runtime renders the appropriate HTML to the browser. The HTML in Listing 5.4 shows the HTML rendered to the browser for WebForm1.aspx.
<TABLE id="Table1" cellPadding="1" width="300" border="1"> <TR> <TD> <span id="Label1">User Name:</span></TD> <TD> <input name="UserName" type="text" id="UserName" /></TD> <TD></TD> </TR> <TR> <TD> <span id="Label2">Password:</span></TD> <TD> <input name="Password" type="text" id="Password" /></TD> <TD></TD> </TR> <TR> <TD></TD> <TD> <input type="submit" name="LogIn" value="Log In" id="LogIn" /> </TD> <TD></TD> </TR> </TABLE>
Each server control is rendered as an HTML 3.2 standard control. The Label control is rendered as a Span tag; the TextBox control is rendered as an HTML text field element; and the Button control is rendered as a Submit button. The Submit button posts the form data back to the server for processing, so when you add a Button server control, it''s rendered as a Submit button. IIS and the ASP.NET runtime keep track of what events to fire for each control based on the page being browsed and the session ID of the browser session.
Each ASPX page you add to your solution has a targetSchema property. Based on the targetSchema, the metadata for the HTML is rendered differently. If you''re targeting Internet Explorer 3.02 or Netscape 4.0, you can change the targetSchema accordingly.
When you click the Log In button, the event delegate that was wired in the code-behind class is fired, and you retrieve the Text property of the UserName and Password TextBoxes. Using the Write member of the Response class, you write the Text values back to the browser. And by calling Response.End, you explicitly ended the page processing of this ASP page.
By default, the internal browser is used to when you browse ASPX pages from the Solution Explorer. You can change this setting to use whichever browser on your machine you want by select the Browse With option from the right-click contextual menu. I normally change the default browser to my external Internet Explorer browser, and when I''m testing a site that needs to work in Netscape, I browse the pages with Netscape Navigator. IE 6.0, Netscape 4.79, and Netscape 6.2 are all happily installed on my machine.
Now that you understand the basics of writing events for server controls, you''re going to use some of the cooler new controls, namely the validation controls that are part of Visual Studio .NET.