Article

Build Your Own ASP.NET Website Using C# And VB.NET, Chapter 2 - ASP.NET Basics

Page: 1 2

Server-Side Include Directives

Server-side include directives enable developers to insert the contents of an external file anywhere within an ASP.NET page. In the past, developers used server-side includes when inserting connection strings, constants, and other code that was generally repeated throughout the entire site.

There are two ways your server-side includes can indicate the external file to include: using either the file or the virtual attribute. If we use file, we specify its filename as the physical path on the server, either as an absolute path starting from a drive letter, or as a path relative to the current file. Below, we see a file server-side include with a relative path:

<!-- #INCLUDE file="myinclude.aspx" -->

virtual server-side includes, on the other hand, specify the file's location on the Website, either with an absolute path from the root of the site, or with a path relative to the current page. The example below uses an absolute virtual path:

<!-- #INCLUDE virtual="/directory1/myinclude.aspx" -->

Note that although server-side includes are still supported by ASP.NET, they have been replaced by a more robust and flexible model known as user controls. Discussed in Chapter 16, Rich Controls and User Controls, user controls allow for developers to create a separate page or module that can be inserted into any page within an ASP.NET application.

Literal Text and HTML Tags

The final element of an ASP.NET page is plain old text and HTML . Generally, you cannot do without these elements, and HTML is the means for displaying the information from your ASP.NET controls and code in a way that's suitable for the user. Returning to the example in Figure 2.1 one more time, let's focus on the literal text and HTML tags:

<%@ Page Language="VB" %>  
<html>  
<head>  
<title>Sample Page</title>  
 
<script runat="server">  
Sub ShowMessage(s As Object, e As EventArgs)  
 lblMessage.Text = "Hello World"  
End Sub  
</script>  
 
</head>  
<body>  
 
<form runat="server">  
<%-- Declare the title as string and set it --%>  
<asp:Label id="lblMessage" runat="server" />  
<% Dim Title As String = "Zak Ruvalcaba's Book List" %>  
<%= Title %>  
</form>  
 
</body>  
</html>

As you can see in the bold code, literal text and HTML tags provide the structure for presenting our dynamic data. Without them, there would be no format to the page, and the browser would be unable to understand it.

Now you should understand what the structure of an ASP.NET page looks like. As you work through the examples in this book, you'll begin to realize that in many cases you won't need to use all these elements. For the most part, all of your development will be modularized within code declaration blocks. All of the dynamic portions of your pages will be contained within code render blocks or controls located inside a <form runat="server"> tag.

In the following sections, we'll outline the various languages used within ASP.NET, talk a little about view state, and look at working with directives in more detail.

View State

As I mentioned briefly in the previous section, ASP.NET controls automatically retain their data when a page is sent to the server by a user clicking a submit button. Microsoft calls this persistence of data view state. In the past, developers would have to hack a way to remember the item selected in a drop-down menu or keep the contents of a text box, typically using a hidden form field. This is no longer the case; ASP.NET pages, once submitted to the server for processing, automatically retain all information contained within text boxes, items selected within drop-down menus, radio buttons, and check boxes. Even better, they keep dynamically generated tags, controls, and text. Consider the following ASP page, called sample.asp:

<html>  
<head>  
 <title>Sample Page using VBScript</title>  
</head>  
<body>  
<form method="post" action="sample.asp">  
 <input type="text" name="txtName"/>  
 <input type="Submit" name="btnSubmit" text="Click Me"/>  
<%  
If Request.Form("txtName") <> "" Then  
 Response.Write(Request.Form("txtName"))  
End If  
%>  
 
</form>  
</body>  
</html>

If you save this example in the WebDocs subdirectory of wwwroot that you created in Chapter 1, Introduction to .NET and ASP.NET, you can open it in your browser by typing http://localhost/WebDocs/sample.asp, to see that view state is not automatically preserved. When the user submits the form, the information that was previously typed into the text box is cleared, although it is still available in Request.Form("txtName"). The equivalent page in ASP.NET, ViewState.aspx, demonstrates data persistence using view state:

Example 2.1. ViewState.aspx

<html>  
<head>  
<title>Sample Page using VB.NET</title>  
<script runat="server" language="VB">  
Sub Click(s As Object, e As EventArgs)  
 lblMessage.Text = txtName.Text  
End Sub  
</script>  
</head>  
 
<body>  
<form runat="server">  
 <asp:TextBox id="txtName" runat="server" />  
 <asp:Button id="btnSubmit" Text="Click Me" OnClick="Click"  
     runat="server" />  
 <asp:Label id="lblMessage" runat="server" />  
</form>  
</body>  
</html>

Example 2.2. ViewState.aspx

<html>  
<head>  
<title>Sample Page using C#</title>  
<script runat="server" language="C#">  
void Click(Object s, EventArgs e) {  
 lblMessage.Text = txtName.Text;  
}  
</script>  
</head>  
 
<body>  
<form runat="server">  
 <asp:TextBox id="txtName" runat="server" />  
 <asp:Button id="btnSubmit" Text="Click Me" OnClick="Click"  
     runat="server" />  
 <asp:Label id="lblMessage" runat="server" />  
</form>  
</body>  
</html>

In this case, the code uses ASP.NET controls with the runat="server" attribute. As you can see in Figure 2.2, the text from the box appears on the page when the button is clicked, but also notice that the data remains in the text box! The data in this example is preserved because of view state:

1327_2
Figure 2.2. ASP.NET supports view state. When a page is submitted, the information within the controls is preserved.

You can see the benefits of view state already. But where is all that information stored? ASP.NET pages maintain view state by encrypting the data within a hidden form field. View the source of the page after you've submitted the form, and look for the following code:

<input type="hidden" name="__VIEWSTATE" value="dDwtMTcyOTAyO  
DAwNzt0PDtsPGk8Mj47PjtsPHQ8O2w8aTwzPjs+O2w8dDxwPGw8aW5uZXJodG  
1sOz47bDxIZWxsbyBXb3JsZDs+Pjs7Pjs+Pjs+Pjs+d2wl7GlhgweO9LlUihS  
FaGxk6t4=" />

This is a standard HTML hidden form field with the value set to the encrypted data from the form element. As soon as you submit the form for processing, all information relevant to the view state of the page is stored within this hidden form field.

View state is enabled for every page by default. If you do not intend to use view state, you can turn it off, which will result in a slight performance gain in your pages. To do this, set the EnableViewState property of the Page directive to false:

<%@ Page EnableViewState="False" %>

Speaking of directives, it's time we took a closer look at these curious beasts!

Working With Directives

For the most part, ASP.NET pages resemble traditional HTML pages, with a few additions. In essence, just using an extension like .aspx on an HTML file will make the .NET Framework process the page. However, before you can work with certain, more advanced features, you will need to know how to use directives.

We've already talked a little about directives and what they can do earlier in this chapter. You learned that directives control how a page is created, specify settings when navigating between pages, aid in finding errors, and allow you to import advanced functionality to use within your code. Three of the most commonly used directives are:

Page

Defines page-specific attributes for the ASP.NET page, such as the language used.

Import

Makes functionality defined elsewhere available in a page through the use of namespaces. You will become very familiar with this directive as you progress through this book.

Register

As you will see in Chapter 16, Rich Controls and User Controls, you would use this directive to link a user control to the ASP.NET page.

You will become very familiar with these three directives, as they're the ones that we'll be using the most in this book. You've already seen the Page directive in use. The Import directive imports extra functionality for use within your application logic. The following example, for instance, imports the Mail class, which you could use to send email from a page:

<%@ Import Namespace="System.Web.Mail" %>

The Register directive allows you to register a user control for use on your page. We'll cover these in Chapter 16, Rich Controls and User Controls, but the directive looks something like this:

<%@ Register TagPrefix="uc" TagName="footer" Src="footer.ascx" %>

ASP.NET Languages

As we saw in the previous chapter, .NET currently supports many different languages and there is no limit to the number of languages that could be made available. If you're used to writing ASP, you may think the choice of VBScript would be obvious. With ASP.NET however, Microsoft has done away with VBScript and replaced it with a more robust and feature-rich alternative: VB.NET.

ASP.NET's support for C# is likely to find favor with developers from other backgrounds. This section will introduce you to both these new languages, which are used throughout the remainder of the book. By the end of this section, you will, I hope, agree that the similarities between the two are astonishing—any differences are minor and, in most cases, easy to figure out.

Traditional server technologies are much more constrained in the choice of development language they offer. For instance, old-style CGI scripts were typically written with Perl or C/C++, JSP uses Java, Coldfusion uses CFML, and PHP is a language in and of itself. .NET's support for many different languages lets developers choose based on what they're familiar with, and start from there. To keep things simple, in this book we'll consider the two most popular, VB.NET and C#, giving you a chance to choose which feels more comfortable to you, or stick with your current favorite if you have one.

VB.NET

Visual Basic.NET or VB.NET is the result of a dramatic overhaul of Microsoft's hugely popular Visual Basic language. With the inception of Rapid Application Development (RAD) in the nineties, Visual Basic became extremely popular, allowing inhouse teams and software development shops to bang out applications two-to-the-dozen. VB.NET has many new features over older versions of VB, most notably that it has now become a fully object-oriented language. At last, it can call itself a true programming language on a par with the likes of Java and C++. Despite the changes, VB.NET generally stays close to the structured, legible syntax that has always made it so easy to read, use, and maintain.

C#

The official line is that Microsoft created C# in an attempt to produce a programming language that coupled the simplicity of Visual Basic with the power and flexibility of C++. However, there's little doubt that its development was at least hurried along. Following legal disputes with Sun about Microsoft's treatment (some would say abuse) of Java, Microsoft was forced to stop developing its own version of Java, and instead developed C# and another language, which it calls J#. We're not going to worry about J# here, as C# is preferable. It's easy to read, use, and maintain, because it does away with much of the confusing syntax for which C++ became infamous.

Summary

In this chapter, we started out by introducing key aspects of an ASP.NET page including directives, code declaration blocks, code render blocks, includes, comments, and controls. As the chapter progressed, you were introduced to the two most popular languages that ASP.NET supports, which we'll use throughout the book.

In the next chapter, we'll create more ASP.NET pages to demonstrate some form processing techniques and programming basics, before we finally dive in and look at object oriented programming for the Web.

Look out for more chapters from Build Your Own ASP.NET Website Using C# And VB.NET in coming weeks. If you can't wait, download all the sample chapters, or order your very own copy now!

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links

Rate This Article

  • 1
    Poor
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
    Great

Comment on This Article

Have something to say?

Post A Comment

You need to be a member of the SitePoint Forums to comment on this post. Sign Up

Already a member? Post using your SitePoint Forums account: