Sams Teach Yourself Visual Studio .NET 2003 in 21 Days

Sams Teach Yourself .Net in 21 Days

By Jason Beres

Hello ASP.NET!

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.

05fig01.jpg

Figure 5.1 Selecting the ASP.NET Web Application template.

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.

05fig02.jpg

Figure 5.2 The HelloWeb application at design time.

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.

05fig03.jpg

Figure 5.3 inetpub directory for the HelloWeb application.

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.

05fig04.jpg

Figure 5.4 File hierarchy of a Web application.

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.

05fig05.jpg

Figure 5.5 Page directives for an ASPX page.

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.

05fig06.jpg

Figure 5.6 Code-behind for an ASPX page.

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.

Table 5.1. Files That Make Up an ASP.NET Web Application

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

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.

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.

05fig07.jpg

Figure 5.7 HTML controls and Web Forms controls in the Toolbox.

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.

Example 5.1. HTML View Comparing Server Controls and HTML Controls

<body>
    <form id="Form1" method="post" runat="server">
        <P>
        <asp:TextBox id="TextBox1" runat="server"></asp:TextBox></P>
        <P>&nbsp;</P>
        <P>&nbsp; <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:

vbnet_icon.gif
Protected WithEvents TextBox1 As System.Web.UI.WebControls.TextBox

c_icon.gif
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:

vbnet_icon.gif
Protected WithEvents HtmlTextBox As System.Web.UI.HtmlControls.HtmlInputText

c_icon.gif
protected System.Web.UI.HtmlControls.HtmlInputText HtmlTextBox;

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:

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 attribute—a <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.

Responding to Server Control Events

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.

  1. Make sure that you're in the Web Forms Designer.
  2. Delete the HTML text field control and the TextBox server control from the form.
  3. From the main menu, select Table, Insert, Table. You are prompted with the Insert Table dialog shown in Figure 5.8.
    05fig08.jpg

    Figure 5.8 Insert Table dialog box.

  4. Click the OK button to add the default table with three columns and three rows.
  5. 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.
  6. 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.
  7. 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.
05fig09.jpg

Figure 5.9 WebForm1.aspx after adding controls.

Your final output will look like Figure 5.9.

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.

Example 5.2. LogIn_Click Event

vbnet_icon.gif
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

c_icon.gif
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.

05fig10.jpg

Figure 5.10 Browsing to the WebForm1.aspx page.

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.

05fig11.jpg

Figure 5.11 Results of the LogIn_Click event.

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.

Example 5.3. HTML Code for the WebForm1.aspx Page

<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.

Example 5.4. HTML Rendered to the Browser from the WebForm1.aspx Page

<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.

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.

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.

Share ThisShare This

Informit Network