Active Server Pages PDF
Active Server Pages PDF
Active Server Pages PDF
Articles
Active Server Pages 1
Active Server Pages/Prerequisites 2
Active Server Pages/Differences between ASP 3.0 and ASP.NET 3
Active Server Pages/Your first page 4
Active Server Pages/Basic ASP Syntax 5
Active Server Pages/Variable Types 8
Active Server Pages/Expressions 13
Active Server Pages/Conditionals and Looping 22
Active Server Pages/Server-Side Includes 28
References
Article Sources and Contributors 32
Article Licenses
License 33
Active Server Pages 1
Table of Contents
• → Prerequisites
• → Differences between ASP 3.0 and ASP.NET
• → Your first page
• → Basic ASP Syntax
• → Variable Types
• → Expressions
• → Conditionals and Looping
• Functions and Subroutines
• Database Access Using ADO
• → Server-Side Includes
• Debugging
References
[1] http:/ / www. w3. org/ TR/ REC-html40/
[2] http:/ / www. 1asphost. com
[3] http:/ / www. google. com/ search?hl=en& lr=& ie=UTF-8& q=free+ asp+ hosting& btnG=Search
[4] http:/ / www. microsoft. com/ windowsxp/ evaluation/ features/ iis. mspx
[5] http:/ / www. apache. org
Content
ASP is delimited with "<% and %>"
within these delimiters is your custom code that is executed in the server.
Here is a small fragment of an ASP code (it outputs "My First ASP" on your browser):
<%
Response.Write "My First ASP"
%>
<%
Dim MyText
<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<%
Dim MyText
%>
<body>
<%=(MyText)%>
</body>
Active Server Pages/Your first page 5
</html>
Content
Active Server Pages or ASP is a scripted language which means that it doesn't have to be compiled in order to run.
Instead, the program code is parsed, interpreted and evaluated in real-time. This means that you do not have to
compile code in order to execute it.
Code is executed by placing it within a web page on a Web server. ASP was developed by Microsoft and because of
this, is only completely reliable on Microsoft's IIS (Internet Information Server.) We encourage you to use Microsoft
IIS to develop Active Server Page code.
Statements
A statement is like a sentence in English, it describes one task for the ASP interpreter to perform. A block of code is
made up of multiple statements strung together on a web page.
There are various types of statements which we will talk about in the future including: "(flow) control, output,
assignment, and HTTP processing.
In Active Server Pages, it is important to realize that each statement must appear on a line by itself. There is no
special delimiter that indicates the end of an ASP statement. Unless you consider the carriage-return as the delimiter,
which you really shouldn't.
You can use the colon character ":" within a program block to place multiple statements on the same line such as:
<%
Response.Write "Error" : Response.End
%>
In practice, it is best to avoid such programming constructs since it will make your code harder to read and maintain.
Another way to include more than one statement on a line is by using multiple code blocks like in the following:
Here, you have two different statements (even though they look like one statement) broken into two different code
blocks. Active Server Pages allows this construct on your web pages since it is sometimes necessary to write code
like this to eliminate white space that appears on your web page.
Active Server Pages/Basic ASP Syntax 6
Variables
One of the hallmarks of a good scripting language is that the variables in the language are loosely typed. This means
that there is minimal type-checking done on the values of the variables your program code uses. Active Server Pages
was built correctly as a scripting language to be loosely typed. This allows you, as the programmer, to worry less
about what type a variable is which frees you from a lot of work converting values and testing for the correct type.
You are not required to declare your variables before you use them (or even at all if you so wish). The one exception
to this rule is when the page directive "Option Explicit" is in effect. If you place the following at the top of your ASP
page, you will be required to declare all variables:
If you don't want this requirement in all your scripts, you can leave it out. It is a useful tool to throw onto a page to
check for mis-spelled or mis-used variable names. If you mis-spelled a variable, you will likely see "variable not
defined".
Variables are declared with a Dim statement and can include a single variable at-a-time or a comma-delimited list of
variable names like shown in the following example:
<%
Dim sPhoneNo
Dim sFirstName, sMidleInitial, sLastName
%>
There is no such thing as a global variable in the ASP language. All variables are specific to the web page they are
processed in. Once the page is done processing the values are lost. One exception to this is the Application object. It
can hold a number of different values, each of which is associated with a string value. Another way is to pass
variables in a web form or part of the URL in the Request object. More information on these topics will be covered
later.
Comments
Comments are notations you can make on your web page within an ASP script block that will not be output on the
web page. For all intents and purposes, they are hidden from your site visitors since they cannot view the ASP source
code for your web pages. This allows you to make comments about what your code is doing.
Active Server Pages uses the quote character (') to define comments. This comment is a "line comment" meaning
that it will comment out everything following it up until the end of the line. There is no multi line comment in ASP.
In order to comment multiple lines, each line must be preceded by a quote (').
<%
' example comment - show the current date
Response.Write Now()
%>
Active Server Pages/Basic ASP Syntax 7
But this doesn't mean that you can't place ASP code inside an included file. So if you include a file called
/lib/common.asp, you can place ASP code inside that file (just like you would a normal ASP page) and it will be
evaluated by IIS and the results will be placed in the calling page.
An interesting note is that your main page can use a ".html" extension and include (via SSI) an ASP page and the
included file will be interpreted and processed as ASP and included in the HTML page.
The two different types of Server-Side includes allow you to retrieve and include files based on the absolute path
(based on the Web site root) or relative to the calling page as shown below;
There are benefits to using both. A good rule of thumb is this: if you expect you will be moving entire folders (or
trees) of your web application then relative paths are more appropriate. If you expect things to stay pretty much
where you created them then you should use absolute paths.
Please note: When using IIS6 (Windows 2003 Server), relative paths are not enabled by default, which will cause
any Server-Side includes using relative paths to cease functioning.
Review Questions
• What are the three different types of script delimiters?
• What file extension must be used when writing an ASP web page?
• Which web server must be used to interpet ASP web pages?
• How do you declare a variable?
• How do you enforce the rule that all variables must be declared?
• What are the benefits of server-side includes?
• When should you use absolute server-side includes (SSI)?
• How do you terminate a statement in ASP?
• What is an "interpreted" scripting language?
• How do you write comments in Active Server Pages?
• How do you make "block comments" in ASP?
• Which database works best with ASP?
Active Server Pages/Basic ASP Syntax 8
External Links
ASP Tutorials [1]
References
[1] http:/ / www. pickatutorial. com/ tutorials/ asp3_0_1. htm
Content
All variables in ASP are loosely typed. This means that you don't need to declare variables with a type. It also means
that you can assign the value of any variable to any other variable. There are a few exceptions to this rule as we will
see.
Basically, every variable in ASP has the major type of Variant. It is "variant" meaning that the type of value it holds
can vary. Basically, the ASP interpreter will handle all conversion between types automatically when you group
more than one variable or type together in a single expression.
Variable Scope
There are three different scopes for variables used in ASP. The first is page scope meaning that the variable is
available for the entire duration. These are typically declared at the top of the page. The second type of variables are
procedure scoped variables which are declared inside a procedure or function declaration. The third type of variables
are scoped with a class definition which is used for object-oriented programming.
<%
Dim sStr1 ' page-scoped variable
....
Procedure DoSomething
Dim mStr2 ' procedure-scoped variable
End Procedure
Function DoSomething
Dim mStr2 ' function-scoped variable
End Function
Class clsTest
Private msStr4 ' class-scoped variable
Public msStr5 ' class-scoped variable
End Class
Active Server Pages/Variable Types 9
%>
Page-scoped variables will be visible to all code included on your web page including procedures and functions. You
can even access page-scoped variables within a class although good object-oriented design would strongly
discourage this practice.
Procedure-scoped variables will only be visible within the procedure in which they are defined. It is perfectly
acceptable to use the same variable name for a page-scoped variable and a procedure-scoped variable. Keep in mind,
that when you do this, you will hide the page-scoped variable and will have no way to access it within the procedure.
Class-scoped variables can only be accessed through an instance of the class. There is no notion of static variables or
static methods in the simplified ASP scripting language. You will need to use the ObjectName.VariableName
syntax in order to access member variables directly. Only variable declared Public can be accessed in this way.
Private class variables can only be accessed by code defined within the class. More information about using classes
in Active Server Pages will be discussed later.
Declaring Variables
To declare a variable, you use the Dim statement for page and procedure-scoped variables. After the Dim statement,
you can put a comma-separated list of variable names. If you prefer, you can just put one variable on each line. This
allows you to add comments about each variable you declare.
<%
Dim sAction ' form action
Dim sQuery ' database query
Dim I, J, K
%>
You should place your variables in a consistent location on the page or within your procedures. Typically, most
people place the declarations at the very top (beginning) of the page or the top of the procedure. Others think it
makes more sense to place the variable declarations right above the location where they are first used.
Primitive Types
When we talk about primitive types, we are talking about low-level variables types that cannot be broken down into
smaller primitive types. Basically, these are the "built-in" variables that Active Server Pages understands.
These are sometimes referred to the "sub-type" of the variable since the major type of the variable is "variant". Each
variable may have one of the sub-types shown in the following table. If you have used other programming
languages, then these primitive types will be very famaliar to you.
Special Values
In addition to the values shown above, the following special values may also be assigned to Active Server Page
variables:
Active Server Pages/Variable Types 11
The empty value is the default value for newly declared variables (never assigned any value.) If tested in a boolean
context, it is equivalent to "false" or tested in a string context it is equivalent to the empty string ("")
Literal Values
Literal values are values you insert into your ASP code and use in expressions. By itself, a literal value has no use,
but when used in a statement such as an assignment or output statement
<%
' examples of literal values
Dim sString, nInt, fFloat, dDate, bBool
You will notice that there is no way to specify a date literal in ASP. Therefore, you need to use a function call to
build a date value using DateSerial or you can use Now() to get the current date and time.
The value for a literal value is bound by the limits specified in the table for primitive types above. If you attempt to
use a value that is outside the acceptable range for any of the types, you will receive an error message indicating this
fact and your ASP page will terminate execution.
Constant Definitions
In some cases, you might want to create "named constants" instead of using literal values all of the time. This is
particularly useful if you create a common include file that will be used in multiple scripts on your site. You define
constants using the Const keyword like so:
<%
Const PI = 3.141592654
Const RECS_PER_PAGE = 25
Const FSO_FORREADING = 1
Const FSO_FORWRITING = 0
%>
It is common practice to use all uppercase variables for your constant definitions although this is not required. It
simply makes your code easier to read and maintain.
Naming Conventions
A naming convention is a standard way of naming all of the variables used on your site. There are various different
methods used for naming variables and a whole chapter could be devoted to this subject. One of the most popular is
hungarian notation where the first letter of the variable name indicates the dominant sub-type for the variable.
Boolean b bIsMale
Byte z zAge
String s sFirstname
Int n nAge
Long l lPageHits
Single f fScore
Double d dMass
Currency m mBalance
Datetime d dExpiration
Object o oFSO
The Microsoft standard proposed for Visual Basic is to use a 3-letter naming convention for their variables. This is a
little more clear for reading and maintaining code. Some would consider this overkill for a light-weight scripting
language.
Active Server Pages/Variable Types 13
Content
An expression is a group of literal and variables which are organized in a structured format using operators. The best
example of an expression is a mathematical expression such as x + 3.
Expressions are made up of a collection of mathematical, comparison, bit-wise and logical operators as well as literal
values and ASP variables which are placed together for evaluation by the ASP Interpreter. Once an expression is
evaluated, it can be assigned to a variable, used as the argument to an ASP procedure or output on an ASP page.
Assignment
One of the most basic statements you can make in ASP is an assignment. This basically evaluates an expression and
places the result into a variable. The equals sign (=) separates the variable that gets the result (on the left side) and
the expression to build the result (on the right side).
<%
Dim nX, dX, sName, bIsAdmin
Dim dDateTime
dDateTime = Now()
nX = 13 + 23 - 10
dx = (5 * nX) / 2.0
sName = "Barney is " & CStr(nX)
%>
Don't worry too much about some of the more complicated expressions found in this example. All of this will be
explained later in this chapter. You should note that the left side of the expression is always a variable. You are only
allowed to put a single ASP variable on the left side of the equals sign.
Evaluation Order
The way an expression is evaluated, depends on the operator precedence. Precedence is kind of an importance
assigned to an operator. Operators that have the highest precedence are evaluated first and those that have the lowest
are evaluated last. When two operators exist that have the same precedence, the operators are evaluated from
left-to-right.
Take for example the following expression:
dX = 6 - 3 * 4 + 2
In this example, you will see we have three different operators. The "+" and the "-" operator have the same
precedence while the multiplication operator (*) has a higher precedence. In this case, the multiplication takes place
first reducing the expression to:
dX = 6 - 12 + 2
Now there are two expressions that have the same precedence. In this case, we evaluate the left-most expression first.
After two more reductions we get the final result:
dX = -6 + 2
dx = -4
You should note also that if we had evaluated the expression from the other direction we would get a completely
different result. This order of evaluation follows the same method used in mathematics (if you remember your basic
algebra.)
Grouping Sub-Expressions
If you want to over-ride the default order-of-evaluation (precedence) for evaluating an expression, you can group
expressions that should be evaluated first in parentheses. You can thing of it as an expression embedded in another
expression or a "sub-expression".
If you remember the example from the previous section, we can modify it to change the order-of-evaluation like so:
dX = (6 - 3) * 4 + 2
And just like in Algebra, we know that we have to evaluate these sub-expressions first. So the first step in reducing
this type of expression is to evaulate the sub-expression:
dX = 3 * 4 + 2
Active Server Pages/Expressions 15
The final reduction will yield a result of 14 which is a completely different result than we got before. Be careful
about how you group your expressions. It can cause a lot of problems and increase the complexity of your code. If
you want to keep your code simpler, you can always create new variables to store the results of sub-expressions.
Mathematical Expressions
The folowing table lists all of the binary mathematical operators. They are "binary" because they require two
arguments. The first argument is on the left-side and the second argument is on the right-side. So the operator "+" in
the expression "5 + 6" has the binary arguments "5" and "6".
+ Addition nX + 5
- Subtraction nX - 5
* Multiplication dX * 1.5
/ Division dX / -1.5
\ Integer Division dX \ 6
% Modulus (remainder) nX % 6
The following table lists all of the unary mathematical operators. A unary operator only has a single argument to act
on.
- Negation -nX
Of course you can combine binary and unary operators in one expression. The results of one binary operation might
serve as the argument to your unary operation.
There are many advanced mathematical functions that can be used to do complex arithmetic which we will talk
about later. These will not be covered in this chapter.
String Operators
When working with strings, Active Server Pages provides a wealth of functions for manipulating strings. But since
we are only talking about operators that may be used in an expression, we will only be dealing with the one string
operator here: the string concatenation operator.
String concatenation means that you want to append one string to another. This operation is a binary operation
meaning that it takes two arguments: the left-side is the string you want to append to and the right-side is the string
that you want to append.
As you can see in the example above, we are using the string concatenation operator to append three string values
together: "Bill", " ", and "Gates". Two of the strings are stored in variables while the space character is just a string
literal.
You may concatenate as many variables as you want together using the string concatenation operator. It has been
shown that string concatenation under Active Server Pages is very inefficient. So if your page is performing slowly
and you have a lot of string concatenations, you should look for ways to eliminate them.
Comparison Operators
Comparision operators, as you might have guessed, are used to compare two different expressions and return a value
of "true" or "false". In most cases the two expressions being comparted will evaluate to a number, but it is possible to
compare string values, dates and booleans.
The following table lists the binary comparison operators. These operators require two expression arguments: one on
the left-side of the operator and one on the right-side. Just like mathematical expressions, you may combine
two-or-more of these expressions together. In the next section we will explain how to these are combined using
logical operators.
= Equality nX = 5
These operators are most commony used in an If Then statement which will take an action based on the boolean
result of an expression. Unless you already have a boolean value stored in an ASP variable, you will need to write an
expression like the following:
Of course, your expression can be as complicated as you want as long as it evaluates to a boolean value.
Logical Operators
Whereas mathematical expressions are used to manipulate numbers, logical operators are used to work with the two
boolean values "true" and "false". These operators are always used to combine two expressions that result in boolean
values.
Active Server Pages/Expressions 17
And True only if both arguments are true, otherwise false nX > 5 And nX < 10
Or True if either argument is true, false only when both arguments are false nX < 5 Or nX > 10
Not Negation, true becomes false and false becomes true Not (nX >
5)
The negation operator basically will give you the opposite value of the expression. So if the expression evaluates to
"true" and you perform the Not operation on it, it becomes "false". Conversely, "false" will become "true" when Not
is applied.
So using these logical operators, we can group many comparison expressions together to create a very complex
expression like so:
The first comparison (nX = 2) looks just like an assignment. You can never put an assignment in an expression like
this. Assignment only occurs at the start of an expression, where the first symbol is an ASP variable which is
followed by the assignement (=) operator.
You will notice that we used parentheses to group the expressions. Even in some cases where parentheses are not
required, it sometimes makes your expressions easier to read when you put them in there.
Bit-Wise Operators
For advanced programming, Active Server Pages has operators for working with individual "bits". A "bit" is the digit
used in the binary number system and was formed from a contraction of the words "binary digit". It can only have
one of two different values: "0" and "1".
In the old days of computer, programmers were severely limited in storage and had to make the most of the available
storage. One way they did this was by combining multiple variables into a single "byte". This has carried through to
modern-day computer systems and this is why we need bit-wise operators.
In computer terms, we talk about "bytes". A byte is composed of 8 "bits" and therefore can have 2 ^
(raised-to-the-power) 8 or 256 possible values. An integer is composed of two bytes so it can have a value of 256 ^ 2
or 65536 possible values.
+-------------------------------------------------------+
| Bit7 | Bit6 | Bit5 | Bit4 | Bit3 | Bit2 | Bit1 | Bit0 |
+------+------+------+------+------+------+------+------+
| 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
+-------------------------------------------------------+
Active Server Pages/Expressions 18
For all of the bits that are set (equal to 1) above, you need to add their integer equivalent to determine the resulting
byte value. So If bits 6, 4, 1 and 0 were set, the equivalent byte value would be: 64 + 16 + 2 + 1 = 83.
Going the other way around, we can convert an integer to binary. We just take the integer value and subtract the
biggest binary value we can and note the corresponding bit. We continue to do this subtracting binary values until we
come up with the resulting bit string:
When working with the bit-wise operators, we sometimes have to convert between binary and integer like this and
vice-versa.
In Active Server Pages, bit-wise operators are only used on numeric expressions to manipulate individual bits. The
numberic expression can evaluate to integers, longs, single or double-precision numbers. After evaluating the
bit-wise operation, the resulting value will be compatible with the orignal arguments.
The following bit-wise operators require two arguments: one on the left-side of the operator and one on the
right-side.
| Bit-wise Or nX | 48
^ Bit-wise Exclusive nX ^ 48
Or
The following operators are "unary" operators meaning they only require one argument. The single expression
argument must be to the right-side of this operator.
~ Bit-wise Negation ~ nX
Truth Tables
Truth tables display the results of the binary operators on a bit-by-bit basis. You can think of each bit in the
arguments being evaluated one-by-one. Bits are matched up based on their position in the bytes. So for a 16-bit
integer, each bit would be operated on individually and the resulting bits would be strung together in the same order
to generate the resulting number.
When viewing these tables, think to yourself "When performing a bit-wise and (&), bit 0 from argument 1 and bit 0
from argument 2 are anded together and the result is X. Next bit 1 from argument 1 and bit 1 from argument 2 are
anded together and the result is Y". And continuing on for all the bits in the arguments.
Active Server Pages/Expressions 19
0 0 0
0 1 0
1 0 0
1 1 1
0 0 0
0 1 1
1 0 1
1 1 1
0 0 0
0 1 1
1 0 1
1 1 0
Arg #1 Result
1 0
0 1
Function Purpose
Time() Get the current time as a datetime value according to the local machine
dTime = Time()
Now() Get the current date AND time according to the local machine
dNow = Now()
DateAdd(Interval, Number, Date Add a specific Number of Interval to the supplied date
DateAdd("d", 3, Now())
DateDiff(Interval, Date1, Date2) Calculate the number of Interval difference between Date1 and Date2
dDaysLeft = DateDiff("d", Now(), dBirthDay)
DatePart(Interval, Number, Date) Retrieve a specific part of a date such as the hour or month
DatePart("yyyy", Now())
DateSerial(Year, Month, Day) Construct a datetime value from the year, month and day components
dBirthday = DateSerial(1998, 12, 23)
Hour(Datetime) Retrieve the hour (in 24-hour military time format [0-23]) for the datetime
value
Hour(Now())
Minute(Datetime) Retrieve the minute (0-59) component for a specific datetime value
nMinute = Minute(dBirthDay)
Information about optional arguments for these functions and valid interval types will be discussed in a later chapter.
You should note that none of the mathematical operators apply to datetime values. You must use the various
conversion and calculation functions above to manipulate dates.
Active Server Pages/Expressions 21
In the example above, we use the line continuation to continue a boolean expression. You may use it to continue any
type of expression or statement. It makes sense to split up long lines for readability. Just be careful how you split
lines so that you don't make the line more confusing to read.
Summary
There are eight different types of operators in ASP:
• Assignment Operators
• Mathematical Operators
• String Operators
• Comparison Operators
• Logical Operators
• Bit-wise Operators
• Grouping Operators
• Line Continuation Operator
All but the assignement operators can be used for building expressions. Operators are evaluated based on precedence
and the grouping operators. If two operators have the same precedence, then the operators are evaluated from
left-to-right.
All date and time values must be manipulated using functions. The mathematical operators are invalid on datetime
values.
Review Questions
• What must be on the left-side of the assignment operator?
• What must be on the right-side of the assignment operator?
• What are the eight major types of operators?
• What is meant by operator precedence?
• Which operator is used to group expressions?
• How are datetime values used in expressions?
Active Server Pages/Expressions 22
Exercises
• Write the conditional expression to test a variable (nSpeed) is less than or equal to the speed limit (nSpeedLimit)
• Write an expression to convert a temperature in farenheit to degrees and vice-versa
• Create a function that calculates the number of days from now until Christmas.
• Create a page that inputs a user's birthday and then calculates how old that person is.
Content
Conditional statements are used by your program to make decisions and decide what the program should do next. An
example of this would be deciding whether a user has entered the correct password for your site by comparing the
password entered with the correct password. If the user passes the test, they are sent to their account management
Web page. If they fail, they are sent back to the login screen with an error indicating the "password is invalid".
This kind of decision making is common in all programming languages. You need to master this aspect of Active
Server Pages in order to write dynamic web applications.
Another important concept is looping. Looping simply means that you repeat the same block of code multiple times.
Since you are going through the code once, going back to the beginning and repeating it again, the direction of
program execution looks like a loop (or a circle) which is why we call it looping. We will introduce you to all of the
looping methods available to you in this chapter.
Program Flow
In general, program flow starts at the very top of the page and continues all the way down the page in the same way
that you read a book. All pages are executed this way in ASP and it makes the code very easy to follow until you get
to conditional statements and looping constructs.
Because of the logical flow of the program, it is easy to trace through your program code and output debugging
information to see what your script is doing as it gets processed by the ASP interpreter. Through use of the
Response.End statement, you can place breakpoints in your script to stop execution at specific points. More about
this will be discussed later.
One topic that will not be covered in this section is procedure and object method calls. We will talk about these in
later sections.
Active Server Pages/Conditionals and Looping 23
Conditionals
A conditional statement is one where an expression is evaluated and based on the result one or more actions may be
taken. This allows you to check for a certain condtion and take a specific action that is required when the condition is
or is not met.
If-Then Statement
The "If-Then" statement is the most basic conditional statement. When put on a single line, this statement says "If
the condition is met, then do this." For example, we could test to see if someone is old enough to vote with:
You may optionally, create an If-Then statement that encloses a block of statements. A block of statements means
more than one statement grouped together. In this case, the entire block of statements will be executed only when the
condition is met. We use indenting in this case to help us read the code and determine where the block starts and
ends.
As you can see in this program block, the If Then statement defines the start of the program block while the End If
statement defines the end of the program block. The program block is indented to make it easier to match the start
and end of the block. All of the statements in this program block will only be executed if the conditional statement is
met (nAge > 18). When it is not, nothing will be done.
If-Then-Else
The If Then statement is great, but what if you want to perform two different actions. One action to be taken when
the condition is met and one action to be taken when the condtion is not met. That is what the If Then Else statement
was create to handle. It basically says: "If the condition is met, then do this, otherwise do this".
As you can see from the example above, you can put the entire If Then Else statement in one line. In many cases,
you will want to avoid this since it tends to make the length of the line very long. Instead, you will probably want to
use the program block form like so:
In this case, only one of the two program blocks will be executed. The first will be executed when the condition is
met. The second will be executed when the condition is not met. So you can think of the If Then Else statement as
saying "one or the other but not both".
Although we are using more than one statement in the program blocks shown above, you could also put a single
statement within each program block. For debugging purposes, you can even have no statements at all within a
Active Server Pages/Conditionals and Looping 24
program block. This allows you to comment out all the statements in a program block and your script will still run no
problem.
You will notice that in the conditional expression for the If Then statement, we did not have to enclose the condition
with parentheses "(" and ")". You can always use parentheses for grouping expressions together but they are not
required to enclose conditional statements.
Select Case
The If Then statements are great if you are just evaluating a "true" or "false" condition. But if you want to evaluate
an expression other than a boolean and take some action based on the result, you will need another mechanism. This
is why the ASP language includes the Select Case statement. This allows you to basically "select" from a list of
many cases, the action to perform.
The cases for a Select Case are all literal primitive values. You must have an "exact match" in order to match a
"case". You may include more than one value to match, but you may not define ranges of values to match, nor may
you define a pattern to match.
This select statement is a little deceiving, because it will only tell you that you can vote if the age is 18 and only 18.
If the age is greater than 18, then none of the specific cases will be matched. Instead, the optional catch-all case
(Case Default) will be executed when the age is greater than 18.
Of course, you don't need to include the Case Default if you don't need it. By leaving it off, you are basically saying
"do nothing if an exact match for a case is not found".
You can use any expression for the Select Case as long as it evaluates to a primitive type. You can not use an object
expression because there is no such thing as an object literal to compare it to. However, you can call an object
method that returns a primitive type and use this as the expression.
In the example shown above, you can see that we are using the carriage return to separate the Case from the block to
be executed. There is no need to terminate this type of program block. It is terminated by the instance of the next
case or the End Select. You may also put the case and the action to perform on the same line by using the colon (:)
as a statement separator:
Looping Constructs
Looping constructs are used for repeating the same step over-and-over again. There may be many reasons to use a
loop. In database-driven web applications, you will often use a loop to iterate over each record returned from a
recordset.
For I = 1 To 10
Response.Write "I = " & I & "<br>"
Next
In this example, we have created a loop that is repeated 10 times. We know it executes exactly ten times because you
can read the statement as "for every whole integer from 1 to 10, do this".
The variable "I" is initialized with a value of 1 and the first repetition of the program block (indented) is executed.
The output will be "I = 1". Don't worry about the "<br>" part, this is just HTML code to create a line break on the
web page.
The second time through the loop, the counter (I) is incremented and takes on a value of 2. So the second line output
by this block is "I = 2". This process repeats as I is incremented one at a time until the counter exceeds the end value.
So in this case, the last line printed will be "I = 10".
In a more advanced case, we can change the way in which the index is incremented. If we wanted the counter to
increment by 2, we would write the For Next loop as follows:
For I = 1 To 10 Step 2
Response.Write "I = " & I & "<br>"
Next
I = 1
I = 3
I = 5
I = 7
I = 9
This time we only get five values output by the loop. This is because we are incrementing the counter by 2 instead of
by 1 (the default.) Notice that we do not have to finish on the ending value (10). After incrementing the counter from
9 to 11, the loop checks to see if we have exceeded the ending value (10) and exits the loop.
You can also count backwards like this:
For I = 10 To 1 Step -1
Response.Write "I = " & I & "<br>"
Next
And of course, you can substitute expressions and variables for the starting and ending values and even the amount
to "step through" the loop:
Active Server Pages/Conditionals and Looping 26
Do While
Another looping construct is the Do While loop which will repeat a block of program code as long as the condition
is met. This is kind of like the If Then conditional statement in that it expects a boolean expression. Here is what it
looks like:
I = 1
bFound = False
Do While I < 10
Response.Write "I = " & I & "<br>"
I = I + 1
Loop
What we have here is a loop that does exactly the same thing as the For Next example shown in the previous
section. Why would you want to use this construct instead of a "for next"? The problem becomes obvious when it is
not easy to determine how many repetitions of the loop you need to do.
X = 239821.33
Do While X > 1
Response.Write "X = " & X & "<br>"
X = X / 2
Loop
In this case, we do not know how many times we will have to divide the value of X by two until we end up with a
value less than or equal to 1. So we just use the Do While loop to handle the logic for us.
Do Until
Almost identical to the Do While looping construct is the Do Until. It works exactly the same way except that it
repeats the program block until the condition evaluates to "true". You could basically do the same thing with "Do
While" by enclosing your expression with Not (expr), but the creators of ASP realized that the code would be cleaner
using this more logical statement.
X = 239821.33
Do Until X <= 1
Response.Write "X = " & X & "<br>"
X = X / 2
Loop
Here, we have created a loop that does exactly the same thing as our "do while". We just reversed the logic of the
conditional statement and changed the keywords to Do Until. In this case, it doesn't make the code that much cleaner
to read. But as we will see later, there are definite cases where you will want to use Do Until.
Active Server Pages/Conditionals and Looping 27
While
The While loop works exactly the same as the Do While except that it has a little shorter construct. Please read the
section on "Do While" to understand how this looping construct works.
X = 239821.33
While X > 1
Response.Write "X = " & X & "<br>"
X = X / 2
Wend
Unlike the "Do" loops, the While loop program block is terminated by the Wend statement.
Summary
Active Server Pages has many different control flow statements to handle the execution of your ASP page. The
conditional statements are: If Then, If Then Else and Select Case. The looping constructs are For Next, Do While,
Do Until and While. Conditional expressions in ASP do not need to be enclosed in parentheses ("(" and ")").
For Next loops manipulate a counter and repeat the program block until the counter exceeds the ending value. Do
While, Do Until and While loops repeat based on the evaluation of a boolean expression (meaning an expression
resulting in the value of "true" or "false").
Review Questions
• What types of conditional statements are available in ASP?
• What types of looping contructs are available in ASP?
• What are the three parameters for a For Next loop.
• How do you count backwards using a For Next loop.
• What loop would you use to repeat until a condition is satisfied?
• What loop would you use to repeat while a condition is satisfied?
• How do you terminate a program block for a Do While loop?
• How do you terminate a program block for a While loop?
Exercises
• Create a For Next loop that outputs integers from 10 to 100 that are evenly divisable by 10
Active Server Pages/Server-Side Includes 28
Content
Server-side includes have been around long before Active Server Pages was ever conceived. Basically, it was
designed as a web server extension that looked for special macros contained inside of HTML comments. Nearly all
webservers support at least some subset of server-side includes. The most useful of these macros is the "server-side
include".
So when a web page is accessed, the web server would first scan the source file (or resource) that the visitor
requested. If no processing macros were found, then this file is simply delivered to the user without modification.
When a macro is found, the web server will do the appropriate processing of the macro (completely replacing the
HTML comment with the appropriate results). All of this is done before the content gets delivered to the user (or the
remote host).
What it Does
The specific processing directive we are interested in here is the server-side include. This allows you to import the
contents of another document into the current one. This is extremely useful for reusing common blocks of ASP code
and HTML. One of the most common uses of this is for creating a website template.
Another popular use is for creating code libraries that can be included in the web pages where you need them. I
typically create a generic site-wide library that all pages must include, a header and footer template, a database
library, an e-mail library and a form processing library. By reusing common code, you can eliminate the errors that
may occur when you copy code from one page to another.
There are two different types of server-side includes we will discuss here: "virtual includes" and "file includes". The
only difference is in the way that they access the directory structure for the website.
Virtual Includes
A virtual include will import the contents of another file based on the document root of the webserver. The path to
the file should begin with a slash (/) which represents the root of the website (not the root of the filesystem).
Internet Information Server (the default webserver for Microsoft Windows) may be configured so that you cannot
use a File Include to import the contents of a file from a parent directory. In this case, you will need to use the
Virtual Include to accomplish this task.
Shown below is an example of two virtual includes used to pull in a header and footer template into the current page.
Contained within an HTML comment (delimitted by ''), you will see the processing directive (#include virtual). The
path and filename inside the quotes is the resource we want to bring into the current document.
<h1>Hello World</h1>
Active Server Pages/Server-Side Includes 29
It is important to note that you can import many different types of files into the current document. You should realize
that the webserver simply replaces the contents of the included file directly into your HTML document. Also, you
cannot embed any preprocessing macros inside an ASP code block (delimitted by <% and %>).
The include process works recursively, so that if you include one file that //also contains// server-side include
directives, then those will be included recursively so that all macros are processed.
File Includes
Another type of include statement is #include file. This statement works just like the virtual include except that the
path to the file must be relative to the directory where the current page resides. In other words, you cannot access the
directory structure starting from the document root (meaning the root of the website.)
Below is the same example as before with the virtual includes replaced with file includes. When running this script
under IIS, you may get an error when trying to access a parent directory in this manner. For this reason, I prefer to
use virtual includes whenever possible.
<h1>Hello World</h1>
Server.Execute
This will execute another Active Server Page file from the website. You can do this conditionally using the If Then
... End If syntax. This is different from the server-side include statement which will be executed wherever it appears.
Another difference between this statement and a server-side include is that all variables, functions and classes
defined in the calling script will not be accessible in the executed script. This is a huge barrier to using this as an
include and it is the main reason why I prefer server-side include to this statement.
If Application("ShowForum") Then
Server.Execute("/module/forum.asp")
End If
I have used this to build a modular web portal application with good success. Through a control panel, the user can
configure which modules they would like to display on their website. The template engine checks this configuration
and pulls in only the modules that we need to display and arranges the layout accordingly.
Active Server Pages/Server-Side Includes 30
Server.Transfer
The Server.Transfer statement is similar to Execute in that it executes an external ASP file on the webserver.
However, unlike Execute, this function does not return control to the calling script. Instead, control is transferred to
the script and, when the script finishes execution, the processing of the request terminates.
This is useful for use as a redirect. Basically, you test for certain conditions in your script and transfer control to
another script based on which condition is met. So maybe you could have a login page that contains a form which
posts to itself. If the user login is authenticated, you can transfer processing to a member control panel.
If bIsLoggedIn Then
Server.Transfer("/account/index.asp")
End If
You should note that if any HTML is output to the browser before the Server.Transfer statement is reached, the
output of the new ASP file will be appended to the HTML that has already been output. While you could do a
standard redirect using the ASP built-in statement Response.Redirect, that would discard any HTML that has
already been output and rebuild the response from the beginning.
Summary
Server-side includes provide a powerful mechanism to reuse code in Active Server Pages. You can use it to create a
website template, code libraries, and HTML modules which may be reused throughout your site.
The two types of include statements are the virtual include and the file include. Use the virtual include to include
ASP or HTML files using a path specifier that begins with a slash (/) denoting the document root of your website.
The file include includes the content of a file with a path specifier that is relative to the directory of the calling
script. The contents of the external file will be imported into the original document before any ASP code is
processed.
Alternatives to server-side include the Server.Execute statement which executes the external file as a stand-alone
script and then combines this output with the output of the calling script. The other is the Server.Transfer statement
which passes control over to the external script permanently (control never returns).
Review Questions
• What does a server-side include do?
• What are the two types of server-side includes?
• What happens if you include a file which contains server-side includes?
• What are some alternatives to the server-side include?
• Explain how these alternatives work to execute external ASP code
Active Server Pages/Server-Side Includes 31
Exercises
• Create the include files (header and footer) for a real simple HTML template
• Write a virtual server-side include to import the HTML template files.
• Write some ASP code to call Server.Execute to display a weather module
• Write some ASP code to call Server.Transfer to log off a user from a member area.
Article Sources and Contributors 32
Active Server Pages/ Differences between ASP 3. 0 and ASP. NET Source: http://en.wikibooks.org/w/index.php?oldid=1360617 Contributors: Chrisbbehrens, Derbeth, Jguk, Kencyber,
Panic2k4, Webaware, 9 anonymous edits
Active Server Pages/ Your first page Source: http://en.wikibooks.org/w/index.php?oldid=1069798 Contributors: Daniel USURPED, Jguk, Kencyber, Mpoulin, Quarx, 7 anonymous edits
Active Server Pages/ Basic ASP Syntax Source: http://en.wikibooks.org/w/index.php?oldid=1479293 Contributors: Adrignola, Dysprosia, EvanCarroll, Jguk, Kencyber, Orion Blastar, 42
anonymous edits
Active Server Pages/ Variable Types Source: http://en.wikibooks.org/w/index.php?oldid=1433571 Contributors: Cjw0527, Jguk, Kencyber, Orion Blastar, 12 anonymous edits
Active Server Pages/ Expressions Source: http://en.wikibooks.org/w/index.php?oldid=998052 Contributors: Jguk, Kencyber, 2 anonymous edits
Active Server Pages/ Conditionals and Looping Source: http://en.wikibooks.org/w/index.php?oldid=998050 Contributors: Jguk, Kencyber, 4 anonymous edits
Active Server Pages/ Server- Side Includes Source: http://en.wikibooks.org/w/index.php?oldid=1479301 Contributors: Adrignola, Kencyber, 2 anonymous edits
Image Sources, Licenses and Contributors 33
License
Creative Commons Attribution-Share Alike 3.0 Unported
http:/ / creativecommons. org/ licenses/ by-sa/ 3. 0/