TechiWarehouse.Com


Top 3 Products & Services

1.
2.
3.

Dated: Aug. 12, 2004

Related Categories

Active Server Pages

 

INTRODUCTION:

 

In this tutorial emphasis is on server-side processing to generate dynamic information for embedding within a Web page. This dynamic content is generated in three ways: through use of the VBScript server language, through built-in, server-side ASP components, and through SQL directives to database servers. As necessary, CSS, DHTML, XML, and JavaScript routines are introduced for client-side processing. The basic hardware and software environment under which this processing takes place is described below.

A Web server running the Microsoft Window 2000 Server network operating system (NOS) includes Internet Information Server (IIS) 5.0 as the platform for serving and managing Web pages. Under IIS, various Internet services are provided, including World Wide Web (WWW) services for delivery of Web pages in response to client requests, File Transfer Protocol (FTP) services for upload and download of files, and Simple Mail Transfer Protocol (SMTP) services for delivery of email messages generated by Web pages.

Active Server Pages (ASP)

is a service running under IIS which permits Web pages to contain scripts coded in the VBScript scripting language that are run on the server to generate the information content to appear on a Web page. This information is embedded in a Web page by the ASP processor prior to sending the page to the browser. Thus, through this server-side scripting capability, Web pages can delivery dynamic content generated on-the-fly as the page is being formatted for delivery to the client.

 

A database server

runs a standard database management system such as SQL Server, Oracle, or even Microsoft Access. IfASP Tutorial the database server is a separate machine from the Web server, then it too must run a network operating system to link to the Internet. For purposes of this tutorial, an Access 2000 database is assumed to run on the Web server rather than on a dedicated database server. This causes fairly minor differences in access to the database, and for all practical purposes, you can imaging the database running on a separate network computer.

 

ASP Components

 

There are two major components of Active Server Pages along with five built-in software objects that permit creation of data-driven Web pages. These components and objects provide a comprehensive set of properties and methods the developer can use to help carry out information processing tasks.

Scripting Component

 

The Scripting Component contains the scripting languages used to create server-side processing scripts along with other objects through which the server's directory and file structures are accessed.

VBScript

The VBScript (Visual Basic Scripting Edition) language is the default language used to create scripts. VBScript is a subset of Visual Basic, yet it contains the functionality needed to produce dynamic, data-driver Web sites in a fairly easy-to-learn, easy-to-apply manner. In addition to providing much of the functionality of standard programming languages, VBScript is the vehicle for activating other objects within the ASP environment.

 

File System Object

One of these objects is the File System Object. This object is created to provide a set of properties and methods for working within the directory system of the server. Through the File System Object you can manipulate folders and files by creating them, naming them, moving and copying them, deleting them, and performing other functions related to managing the folders and files of your Web site.

 

Text Stream Object

In addition to working with directories and their contents, the File System Object is used to create Text Stream Objects. These objects are used to read and write text files. Through the Text Stream Object, you can pull information from text files and display it on a Web page, assuring that the page always contains the latest information as reflected in the contents of the files. Or, information collected through a Web page form can be used to update existing text files, thereby assuring the currency of information stored in text files.

Active Data Objects (ADO) Components

There are two primary ActiveX Data Objects (ADO) through which links are made to databases and through which information is read from or written to database tables.

Connection Object

Connection Objects include the properties and methods for linking scripts with databases. These connections are established through ODBC (Open DataBase Connectivity) drivers that are associated with various types of database management systems. There are ODBC drivers for the popular DBMSs such as Microsoft Access, Microsoft SQL Server, and Oracle. Therefore, scripted Web pages can gain access to most of the Database Management Systems on the market.

Recordset Object

Recordset Objects represent the contents of databases linked to through Connection Objects. It is through Recordset Object properties and methods that access is provided to the tables of a database and through which you can read from, write to, and update the contents of these tables.

ASP Built-in Objects

In addition to the scripting and data access components there are five built-in ASP objects that provide functionality for the Web page author:

Server Object.

The Server Object is the mechanism through which VBScript creates File System Objects, Connection Objects, Recordset Objects, and other objects need by the script.

Request Object

The Request Object is used to access data sent from the browser, most often transmitted from forms appearing on the Web page.

Response Object

The Response Object is used by a script to send information from the server to the browser. Information appearing on a Web page is produced by the Response Object.

Session Object

The Session Object is used to manage user sessions. A session is established when the user first arrives at a Web site and Session Objects can be used to track activities of users as they navigate through the site.

Application Object

The Application Object is used to manage the entire Web application. It is used to keep track of users or to maintain information pertinent to all visitors to the site.

Much of the scripting necessary to process data on the server involves calling upon these ASP objects to set their properties or activate their methods. These objects provide a wide range of functionality and remove from the Web developer the need to code detailed instructions to accomplish the tasks. Most of this tutorial, in fact, is coverage of these objects and the properties and methods available to perform information processing activities.

ASP Scripts

In order to activate ASP components and to use its objects, a script is placed on the Web page along with the HTML codes specifying how the generated information is to be formatted for display in the browser. This script is written in the VBScript language and is contained inside the special symbols <% and %> to indicate its presence to the server:

 

<html>
<head>
  <title>Page Title</title>
</head>
<body>

Text...
<%
This is a script
%>
Text...

</body>
</html>

Web pages containing scripts must be saved with the special file extension .asp to inform the server that this is a scripted page. When the ASP page is retrieved by the server, it is not sent directly to the browser as is the case with normal .htm pages. Instead, the page is routed to the ASP processing routine (asp.dll) where the scripts on the page are run and the information produced by the scripts are generated.

The server "composes" an HTML page, using the HTML codes appearing on the page and inserting the information generated by the scripts. The end result is a page entirely composed of HTML and text information where much, if not all, of the text information has been generated by the scripts. This final HTML page is then delivered to the browser. If you view the source listing of the page in the browser, you see only the final results of processing. You do not see any of the script contained on the original page.

 

Running Active Server Pages

Scripted pages (.asp pages) must be run under the http protocol. This means that you cannot open these pages as files in your browser and view the results as you can with standard .htm pages. They must be run from a server and accessed with a URL beginning "http://..."

 

Displaying Server Values

The manner in which Active Server Pages operates can be illustrated very simply by using ASP along with some built-in VBScript functions to play with the system time and date. It is assumed that you are familiar with the Visual Basic language, of which VBScript is a subset. Even if you don't know Visual Basic, you still should be able to follow along with the coding.

You need to know that the system time is retrieved from the server with the VBScript function Time and that the system date is retrieved with the function Date. The following ASP script example retrieves these values from the server and embeds them within this HTML page to produce output shown below:

The time is 4:24:54 PM and the date is 5/2/2002.

These time and date values are "live," meaning that they are retrieved from the server the instant you load this page. If you reload the page, you should see a different time reported.

The code for this page contains the following line to produce the time and date values:

<b>The time is <%= Time %> and the date is <%= Date %>.</b>

This is standard HTML coding for the text along with the VBScript Time and Date functions (coded in red) embedded within the HTML. The result of script processing is that the system time and date are retrieved by the server and embedded within the surrounding HTML text.

Identifying Scripts on a Web Page

Server-side scripts are included on a Web page by coding them between the special symbols <% and %>. Any number of VBScript statements can be coded between these two symbols. When the server encounters such scripts, it performs the indicated processing. In this example, the server executes the VBScript Time function in the first script and executes the Date function in the second script.

Embedding Server Values

In most cases you will want the results of server processing displayed on the Web page when it is delivered to the client. Server-generated values can be displayed on the page by including an equal sign (=) following the first script symbol. In other words, enclose the output value between <%= and %> symbols, as is done in the above scripts. The equal sign indicates that the server should display the results of processing at this script location on the page. So, the server embeds the resulting time and date values within the HTML code at the locations of the scripts. This method of displaying server output is used when the value is to appear inside HTML that is hard coded on the page.

Using the Response.Write() Method

There is a second method that can be used to write script output to a Web page. This method is used when a script needs to write HTML code as well as server values to the Web page. Yes, that's correct. A script can produce HTML code in addition to producing data values; and the code and values can be written to the page prior to delivery to the client.

We'll rewrite the above script in a manner that more resembles standard programming to give you a better look at the difference between scripts that simply display server values and scripts that contain both processing and display statements.

<%
MyTime = Time
MyDate = Date
Response.Write("<b>The time is " & MyTime)
Response.Write(" and the date is " & MyDate & ".</b>")
%>

 

In this example, the Time and Date functions are assigned to variables MyTime and MyDate at the beginning of the script. These variable values, along with the HTML code to display them, are written to the page through a pair of Response.Write statements.

Recall that one of the built-in objects supplied with the ASP processor is the Response Object. This object contains properties and methods that are used to send information from the server to the browser. One of the methods supplied with the Response Object is the Write() method, whose general format is shown below:

Response.Write("string" | variable)

Response.Write is used to write either or both literal character strings (enclosed in quotes) and server values, all enclosed within parentheses. When both types of output are included in the statement, they are strung together with the VBScript concatenation symbol: & (ampersand).

The first of the above Response.Write statements writes a character string followed by a server variable: Response.Write("<b>The time is " & MyTime)

The character string includes HTML code and text which is concatenated with the value stored in variable MyTime. The two values are written to the Web page at the exact location where the script appears.

The second Response.Write statement writes additional text to the page followed by the MyDate server variable, and ending with an HTML character string: Response.Write(" and the date is " & MyDate & ".</b>")

The output of these statements is identical with the first script: The time is 4:24:54 PM and the date is 5/2/2002.

You should note that the single line of output is produced with two different Response.Write statements. This is not necessary. It is used here to illustrate the fact that the statements simply write something to the Web page. The manner in which the output is formatted (whether as a single line or as two lines or more) is determined by the HTML code that is written, not by the number of statements. We could, of course, have written the entire output with a single statement,
Response.Write("<b>The time is " & MyTime & " and the date is " & MyDate & ".</b>")

or we could have used separate statements for each piece of output:
Response.Write("<b>The time is ")
Response.Write(MyTime)
Response.Write(" and the date is ")
Response.Write(MyDate)
Response.Write(".</b>")

Whether you use the embed method of displaying server output by enclosing it between <%= %> symbols or whether you use Response.Write statements to display script output will generally be determined by your processing and display needs. If you are simply displaying a server value inside HTML that is already hard-coded on the page, you'll normally use the first method. If your script needs to write HTML code as well as server values, then the second method is preferred.

 

 

Date and Time Functions

We'll continue with some additional examples of VBScript Date and Time functions to help elaborate the ideas behind server-side scripting. In the following example we use the functions:

Function Returned Value
Date Returns the system date in the format mm/dd/yy.
Time Returns the system time in the format hh:mm:ss AM|PM.
Now Returns the system time and date in the format
mm/dd/yy hh:mm:ss AM|PM.
Hour(Time) Returns the hour of the day in 24-hour (military) time.
Year(Date) Returns the year portion of the system date in the format 9999.
Month(Date) Returns the numeric month of the year (January = 1).
MonthName(Month(Date)) Returns the name of the month.
Day(Date) Returns the numeric day of the month.
WeekDay(Date) Returns the numeric day of the week (Sunday = 1).
WeekDayName(WeekDay(Date)) Returns the name of the day of the week.
DateAdd() Adds date and time intervals to derive a new date or time.
DateDiff() Returns the difference between dates and times.
FormatDateTime() Formats display of dates and times.

Note that several of the returned values are given by functions applied to other functions. For instance, MonthName(Month(Date)) returns the name of the month. To derive this value, the Month function is first applied to the Date function to extract the numeric month of the year (January = 1) from the system date, which is in the format mm/dd/yy. Then the MonthName function is applied to this numeric result to get the name of the month.

We'll put these functions together inside a script that appears next on the page to produce the following output:

 

Good Afternoon. The time is 4:25:08 PM and the date is Thursday, May 2, 2002.

Script Decision Making

The first part of the message is a greeting. Currently the greeting is "Good Afternoon" but at other times of the day it may be different. If the current time is prior to 12:00 noon, then the greeting is "Good Morning." If the time is between 12:00 noon and 6:00 PM, then the greeting is "Good Afternoon." If the time is after 6:00 in the evening, then the greeting is "Good Evening."

We can specify that a particular greeting be displayed by coding a script to check the hour of the day and then format the appropriate greeting. To do so, we need to use the VBScript If...End If decision-making structure. Just as in Visual Basic, VBScript contains an If...Else...End If structure. Its general format is

If condition test Then
    ...statements

[ ElseIf condition test Then
    ...statements ]
...

End If

with condition tests formed using the conditional operators

< less than
= equal to
> greater than
<= less than or equal to
>= greater than or equal to
<> not equal to

and with compound condition tests constructed with the logical operators AND
OR
NOT

We begin our script with condition tests to determine within which of the three time ranges the current hour of the day falls. In order to determine the current hour of the day, we use the Hour(Time) functions. The Time function returns the current system time in the format hh:mm:ss; the Hour function applied to this value extracts the hour portion, converting it to military (24-hour) time. Here is the start of our script:

<%
If Hour(Time) < 12 Then
  Greeting = "Good Morning"
ElseIf Hour(Time) < 18 Then
  Greeting = "Good Afternoon"
Else
  Greeting = "Good Evening"
End If
%>


First, we check whether the current hour is less than 12 (before noon). If so, then we store the character string "Good Morning" in the variable named Greeting. If this condition test is false, we proceed to check whether the current hour is less than 18 (6:00 in the evening). If so, then we store the character string "Good Afternoon" in the variable named Greeting. Otherwise, it's later than 6:00 in the evening and we store the character string "Good Evening" in the variable. At the completion of this portion of the script, one of the text strings is stored in the variable depending on the hour of the day.

Displaying the Message

This script represents all of the "processing" that needs to be done prior to displaying the message. We can now display the entire message by writing the greeting along with the other server values and text to format the line. The script is expanded to include the necessary Response.Write() statements to write to the page:

<%
If Hour(Time) < 12 Then
  Greeting = "Good Morning"
ElseIf Hour(Time) < 18 Then
  Greeting = "Good Afternoon"
Else
  Greeting = "Good Evening"
End If

Response.Write(Greeting & ". ")
Response.Write("The time is " & Time)
Response.Write(" and the date is " & WeekDayName(WeekDay(Date)) & ", ")
Response.Write(MonthName(Month(Date)) & " " & Day(Date) & ", ")
Response.Write(Year(Date) & ".")
%>


We have decided to use multiple Response.Write() statements to output a short section of the line at a time. It makes the script easier to read without affecting the display. In the first statement the contents of variable Greeting is written along with a literal period and blank space prior to the beginning of the second sentence. In the second statement the text string "The time is " is written, followed by the current system time represented by the Time function. The third statement outputs the text string " and the date is " followed by the name of the day of the week, followed by a comma and a space. The fourth statement writes the month name, a blank space, the day of the month, a comma, and a space. The final statement displays the year, followed by a period at the end of the sentence.

The message should be displayed centered on the page and in bold blue font. So, let's write some HTML formatting code surrounding the message.

<%
If Hour(Time) < 12 Then
  Greeting = "Good Morning"
ElseIf Hour(Time) < 18 Then
  Greeting = "Good Afternoon"
Else
  Greeting = "Good Evening"
End If

Response.Write("<div style='font-weight:bold;color:blue;text-align:center'>")
Response.Write(Greeting & ". ")
Response.Write("The time is " & Time)
Response.Write(" and the date is " & WeekDayName(WeekDay(Date)) & ", ")
Response.Write(MonthName(Month(Date)) & " " & Day(Date) & ", ")
Response.Write(Year(Date) & ".")
Response.Write("</div>")
%>


The first and last Response.Write() statements write a <DIV> tag surrounding the message. This tag is used to apply various styles to the enclosed message. The tag is written to the page by the script; still, this has the same effect as if the tag were hard coded on the page. You might notice that the style specifications themselves are enclosed in a set of apostrophes. This is necessary in order to differentiate this text string from the enclosing quotes associated with the Response.Write string. You can code quotes inside of quotes as long as you alternate between quote marks and apostrophes.

Remember that the server runs the script prior to sending the page to the browser. Therefore, all that is returned to the browser is the results of script processing. If you were to take a look at your browser's source listing for this page, all you would see are the lines:

<div style='font-size:11pt; font-weight:bold; color:blue; text-align:center'>
Good Evening. The time is 9:08:08 PM and the date is Friday, June 15, 2001.
</div>

The ASP processor runs the script and writes its output to the page. It does not return the script to the browser.

Embedding Server Values

Recall that using Response.Write is one of two methods of displaying script output on a Web page. If you wish to display output embedded within hard coded HTML, then you can use the <%= %> method to insert the values inside the code. The following code, for example, produces the identical output to the above script.

<%
If Hour(Time) < 12 Then
  Greeting = "Good Morning"
ElseIf Hour(Time) < 18 Then
  Greeting = "Good Afternoon"
Else
  Greeting = "Good Evening"
End If
%>

<div style="font-weight:bold;color:blue;text-align:center">
<%=Greeting%>. The time is <%=Time%> and the date is
<%=WeekDayName(WeekDay(Date))%><%=MonthName(Month(Date))%> 
<%=Day(Date)%><%=Year(Date)%>.
</div>

The If statement is enclosed within script symbols as in the previous script so that the server can store the correct greeting in the variable. The output values, however, are embedded inside HTML that is hard coded on the page. Wherever the <%= %> symbols appear on the page, the actual value stored in the enclosed variable (Greeting, in this case) or the actual value generated by the enclosed code (function calls in these cases) are substitued for the code and appear as part of the HTML text that is returned to the browser.

Again, you can use either output method depending on processing or display circumstances that arise.

Comparing Dates and Times

Intervals between dates and times are derived from the functions DateDiff() and DateAdd(). Both functions use the following interval strings to indicate the unit of measurement.

Interval Description
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week of year
h Hour
m Minute
s Second

The DateDiff() function requires three arguments:

DateDiff(interval, first date, second date)

 

where interval is the unit of measurement as an interval string and first date and second date are literal dates or the system date. For example, the following function returns the number of days until Christmas:

 

There are <%=DateDiff("d",Date,"12/25/2001")%> days until Christmas.

 

 

There are -128 days until Christmas.

 

The "d" parameter specifies the measurement in days, the Date function retrieves the current date, and "12/25/2001" is the comparison date.

The DateAdd() function also requires three arguments:

DateAdd(interval, multiplier, date)

 

where interval is the unit of measurement as an interval string, multiplier is the number of units to add, and date is a literal date or the system date. For example, the following function returns the time 2 hours from now:

 

In two hours it will be <%=DateAdd("h",2,Time)%>.

 

 

In two hours it will be 6:25:08 PM.

 

The "h" parameter specifies the measurement in hours, the 2 specifies the addition 2 hours, and Time is the current system time.

Formatting Dates and Times

By default, dates are displayed in short date format (5/2/2002) and times are displayed in long time format (4:25:08 PM). These displays can be formatted by using the FormatDateTime() function to specify either a short or long date or time.

The short date is <%=FormatDateTime(Date,0)%>.
The long date is <%=FormatDateTime(Date,1)%>.

The short time is <%=FormatDateTime(Time,4)%>.
The long time is <%=FormatDateTime(Time,0)%>.
The short date is 5/2/2002.
The long date is Thursday, May 02, 2002.

The short time is 16:25.
The long time is 4:25:08 PM.

By passing the date parameter 0 (short) or 1 (long), the function returns the appropriately formatted date. By passing the time parameter 4 (short) or 0 (long), the function returns the appropriately formatted time.

 

Server Variables

The ASP Response Object supplies several useful properties and methods for producing server output destined for a Web page. For example, we have used the Response.Write() method to display server data and to write HTML code to a page. As we proceed through this tutorial, other features of the Response Object are introduced as needed.

The ServerVariables Collection

 

Another useful built-in ASP object is the Request Object. This object deals with server input, with information transmitted from a Web page to the server. This information is packaged within collections, which are arrays of values collected from a user's URL request for a Web page. Among other features, the Request Object contains the ServerVariables collection. This set of items contains information taken from HTTP headers that are transmitted from the browser to the server when the user makes a URL request. The collection contains information about the browser being used along with other information about the page being accessed.

Among the 50 or so items in the ServerVariables collection, the following ones are particularly useful:

ServerVariable Description
HTTP_REFERER The URL of the page containing the link to this page.
HTTP__USER_AGENT The type of browser being used by the visitor.
REMOTE_ADDR The IP address of the visitor.
SERVER_NAME The IP address or Domain Name of the server.
SCRIPT_NAME The virtual (Web) path to and identification of the current page.
PATH_TRANSLATED The physical path to and identification of the current page.

Values in this collection are accessed by using the reference

Request.ServerVariables("variableName")

This is a reference to the Request object, the ServerVariables collection, and the specific name of the variable in the collection. We can display the value of any variable by using this reference within a Response.Write() statement. Thus, if we code

<% Response.Write(Request.ServerVariables("HTTP_USER_AGENT")) %>

we produce the output Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)

which is the value of the server variable HTTP_USER_AGENT identifying the browser being used when a request was made for this page. This reference is, of course, to the browser you are currently using.

Determining Browsers

 

For certain ASP applications it may be necessary to know which browser the user is running. Because of incompatibilities between Internet Explorer and Navigator and because of differences in their versions, you may need to provide different coding for different browsers and versions. Therefore, you can include an ASP script on a page to determine a user's browser and to provide alternate coding or alternate pages for different browsers. The HTTP_USER_AGENT server variable is used to discover these browser differences. The values that are returned by this variable are similar to the following:

Internet Explorer: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Win 9x 4.90)
Navigator: Mozilla/4.51 [en] (Win95; I)

It is a matter, then, of parsing these string values to determine which browser is being used.

Among other differences in the values, note that Internet Explorer is identified by the substring "MSIE" which appears for all versions of that browser. Navigator does not produce this substring. So, one way to identify Internet Explorer is to see if "MSIE" appears in the value returned by the HTTP_USER_AGENT variable. Otherwise, this is Netscape Navigator or a compatible browser.

VBScript has an InStr function that checks for the presence of a substring within a text string. The general format for this function is:

InStr(string,substring)

The function checks for the presence of substring within string. If it locates the substring of characters, it returns the starting postion of the substring within the string. If the substring of characters is not present within string, then the value 0 is returned. So, the following script

<%
If InStr(Request.ServerVariables("HTTP_USER_AGENT"),"MSIE") <> 0 Then
   Response.Write("<b>You are using Microsoft Internet Explorer.</b>")
Else
  Response.Write("<b>You are using Netscape Navigator.</b>")
End If
%>

produces the following output for the browser you are currently using:

You are using Microsoft Internet Explorer.

Thus, at the top of your ASP pages you can code a routine such as the following:

 

<%
If InStr(Request.ServerVariables("HTTP_USER_AGENT"),"MSIE") <> 0 Then
     Browser = "IE"
Else
     Browser = "NN"
End If
%>

 

Then, throughout your page you can apply different processing or formatting by checking the value of variable Browser:

<% If Browser = "IE" Then %>
  ...apply Internet Explorer processing or formatting
<% Else %>
  ...apply Navigator processing or formatting
<% End If %>

 

Determining The Browser Version

You can also determine the browser version by referencing the HTTP_USER_AGENT substring containing the version number. In modern browsers these values are at postion 31 (for three characters) in Internet Explorer and position 9 (for four characters) in Navigator: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Win 9x 4.90)
Mozilla/4.51 [en] (Win95; I)

You can pick out these version numbers using the VBScript Mid function to extract a substring from a string. Its general format is

Mid(string, start, length)

where string is the string containing the substring of characters, start is the starting position of the substring, and length is the number of characters to extract as the substring. The following script first checks to see whether the visitor's browser is Internet Explorer or Navigator and then extracts the version number substring, assigning it to variable Version:

<%
If InStr(Request.ServerVariables("HTTP_USER_AGENT"),"MSIE") <> 0 Then
  Browser = "Internet Explorer"
  Version = Mid(Request.ServerVariables("HTTP_USER_AGENT"),31,3)
Else
  Browser = "Navigator"
  Version = Mid(Request.ServerVariables("HTTP_USER_AGENT"),9,4)
End If
Response.Write("<b>Your browser is " & Browser & " " & Version & ".</b>")
%>

Your browser is Internet Explorer 5.0.

Determining Other Header Information

There is additional useful information in the URL headers transmitted to the server. The following table shows this information pertinent to your current visit to this page. The values displayed in bold are the real-time server values displayed with Response.Write() statements.

ServerVariable Current Value
HTTP_REFERER http://www.it.maconstate.edu/tutorials/ASP/menu.htm
(The URL of the page containing the link to this page.)
REMOTE_ADDR 202.179.143.8
(The IP address of the visitor.)
SERVER_NAME www.it.maconstate.edu
(The IP address or Domain Name of the server.)
SCRIPT_NAME /tutorials/ASP/ASP02/asp02-03.asp
(The virtual (Web) path to and identification of the current page.)
PATH_TRANSLATED D:\Tutorials\ASP\ASP02\asp02-03.asp
(The physical path to and identification of the current page.)

 

Form Design

Forms processing is a very important feature of Active Server Pages. It is through the use of forms that users interact with your Web pages and through which you can collect information for personalizing pages for your visitors. In a broader information processing sense, forms provide for data entry into your processing systems. They are the primary mechanism for capturing the data that your scripts process to generate information, to update files and databases, and to respond to user requests for information output.

As you proceed through this tutorial you will learn about all aspects of forms processing. We will have occasion to discuss and demonstrate all of the controls, or data entry mechanisms, that can be coded on forms. You probably have encounter most of these in your meanderings across the Web: text entry fields, clickable buttons, radio buttons, checkboxes, drop-down menus, and the like. We will cover all of these in the following lessons. For now, we will consider a couple of common controls--text entry boxes and forms submission buttons.

An Example Application

This first example of forms processing is a logon application. It involves two pages. The first page, named "logon.asp," contains a form for submitting an account and password. The visitor enters this information and clicks the "Submit" button to submit the form information for checking. logon.asp

Logon Page

Account:
Password:

The second page is a site welcome page named "welcome.asp". The form information is submitted to this page for account and password checking. If the correct account and password is submitted, then the page is viewable. If either the account or password is incorrect, the visitor is returned to the logon.asp page. welcome.asp

Welcome Page

Welcome to my page.

The <FORM> Tag

The HTML coding for the logon.asp page is shown below. A form is provided for entering an account and password, and a button is provided for submitting this information for checking. A table has been used to align items on the form.

logon.asp

<html>
<body>

<h3>Logon Page</h3>

<form name="Logon" action="welcome.asp" method="post">
  <table border="0">
  <tr>
    <td>Account: </td>
    <td><input type="text" name="Account" size="10"></td>
  </tr>
  <tr>
    <td>Password: </td>
    <td><input type="password" name="Password" size="10"></td>
  </tr>
  </table>
  <input type="submit" name="SubmitButton" value="Submit">
</form>

</body>
</html>

HTML form controls are displayed on a Web page by coding them within <FORM>...</FORM> tags. These tags surround the form controls; however, they do not need to enclose them "tightly." In other words, the <FORM> tags need not immediately precede the first control nor immediately follow the last control. If your page contains a single form, you can code the opening <FORM> tag right after the <BODY> tag and code the closing </FORM> tag immediately before the closing </BODY> tag. Then, your controls can appear throughout the body of the document, intermixed with other HTML tags or text.

The <FORM> tag contains three important attributes for forms processing:

The Name Attribute. All forms should be named. Although this is not a requirement for the current exercise, it still is a good habit to get into. It will become necessary to name a form when you wish to perform browser-side validation of data, a topic we will consider throughout the remainder of this tutorial. Forms are named by coding Name="formName" within the <FORM> tag. You can assign any name you wish to the form. In this example name="Logon" is used.

The Action Attribute. The Action="url" attribute identifies the location and name of the page to which information from the form is sent for processing. If the page that will process the data is in the same directory as the page containing the form, then the URL in the Action parameter is simply the name of that page. Otherwise, it can be a full URL specifiying a Web address on a different server or in a different directory on the same server. In this example, the account and password entered by the visitor is sent to the welcome.asp page in this same directory: action="welcome.asp"

The Method Attribute. The Method="GET|POST" attribute specifies the means used to send the form data to the page where they will be processed. There are two methods from which to choose.

The GET method is the older-style way of sending data. In this case, the data from the form are appended to the end of the URL for the page to which the data are being sent (the URL in the Action attribute). The form data comprise a text string that is concatenated to the URL following a question mark (?). You probably have seen this happening in your browsing of the Web. This method is no longer preferred since there is a limit to the number of characters that can be sent, and there is little privacy when the data from the form appear directly in the URL address box in the browser.

The POST method gets around these two objections. It sends the form data as a separate text string which does not appear in the browser address box; plus, you can transmit as many characters as are required to send your entire form to the Action page for processing. Unless you have a good reason for not doing so, always use the POST method. In this example method="post" is used.

Form Fields

Forms are composed of fields, or form controls, through which the user enters data, makes choices, and submits information. The manner in which the information is collected depends upon the type of form element coded within the <FORM> tags. Although we will have occasion to review all of the types of form elements throughout this tutorial, for present purposes we will consider only the three types needed for the logon application. This will give you a good understanding of the general method for processing forms without complicating the coding with a full range of form fields.

The Account Field. The example page requires a text box within which the user enters an account. This is a standard text box created using an <INPUT TYPE="TEXT"> tag with an assigned name and size attribute.

<input type="text" name="Account" size="10">

The Password Field. A password field appears as a standard text entry box; however, when characters are typed in the field, they are echoed as asterisks (*) or bullets to maintain privacy of the entered data. A password field is created using an <INPUT TYPE="PASSWORD"> tag. The field needs to be assigned a name and its size can be changed from the default 20-character width.

<input type="password" name="Password" size="10">

In this example and for all forms that you create you must be sure to assign names to form fields. These names are needed for server processing. In addition, you can control the physical size of the the fields by coding SIZE attributes, and you can restrict the maximum number of characters permitted to be typed by coding the MAXLENGH attribute.

The Submit Button.
A submit button, when clicked, causes the action specified by the ACTION parameter of the <FORM> tag to take place. In other words, clicking a submit button transmits the data from the form to the indicated page. A submit button is created by coding an <INPUT TYPE="SUBMIT"> tag. In addition, you need to name the button for script reference and assign a value that serves as the label appearing on the button.

<input type="submit" name="SubmitButton" value="Submit">

Once the form page is created, it is ready to be activated. Recall that this form submits account and password information to the welcome.asp page. There, these values are checked for authorization to view that page. If an incorrect account and/or password is submitted, the user is returned immediately to the logon.asp page without an opportunity to view the welcome.asp page.

 


Form Submission

Information entered onto a form is submitted for processing by clicking the form's submit button, <INPUT TYPE="SUBMIT">. The information is then transmitted to the page identified in the ACTION attribute of the <FORM> tag. When this URL request and the accompanying form data arrive at the server, the targeted page is retrieved and the data are made available to it for processing.

Name/Value Pairs

Data from a form are transmitted to the server as a series of name/value pairs. This means that the name of each form element (as appearing in the NAME attribute of the tag) is associated with the value of that element (as typed or selected by the user). The name/value format used for transmission is name=value. There are as many of these name/value pairs as there are elements on the form, and the pairs are concatenated with ampersands (&) to form a text string that resembles the following: name1=value1&name2=value2&name3=value3....

Any blank spaces appearing in the names or values are substituted with the plus (+) character to form a non-breaking string of name/value pairs. In the current application assume that the user entered the account "myaccount" and the password "xyzzy". The resulting name/value string delivered to the server would be:

Account=myaccount&Password=xyzzy&SubmitButton=Submit

Note that both field and button names and values are transmitted. Although shown here in the same order in which the elements appear on the form, there is no guarantee that the order of the name/value pairs that arrive at the server will be the same as it is on the form.

The Request.Form Collection

The ASP Request Object provides valuable assistance in gathering form information transmitted to the server by putting it into a structure for convenient script processing. The Request Object intercepts the name/value string, parses the string into names and associated values, and places this information into a Request.Form Collection. This collection can be visualized as an array of submitted values, each indexed by its associated form field name.

Once the data values are in the Request.Form Collection they can be easily referenced by their names using the syntax:

Request.Form("fieldName")

where fieldName is the name assigned to the field in the form. Thus, the reference Request.Form("Account") points to the value entered into the Account field; the reference Request.Form("Password") points to the value entered into the Password field; and the reference Request.Form("SubmitButton") is a reference to the value assigned to the Submit button. From a programming standpoint, Request.Form("fieldName") acts like a program variable that references a value stored in that variable.

To summarize our application so far: The user calls up the logon.asp page, which is retrieved by the server and sent to the user's browser where the form is displayed. The user then enters information into the Account and Password fields and clicks the Submit button. This submission triggers a URL request to the server for the welcome.asp page (action="welcome.asp"). In addtion, the form attribute method="post" transmits a separate name/value data stream to the server representing the field names and entered values typed by the user. This name/value string is received and parsed by the ASP Request Object, which places the values in its Request.Form Collection where they can be referenced by the names of their associated form fields. This Request.Form Collection is now available to the welcome.asp page as a means for checking the submitted values from the form.

 

Processing Form Information

When a form is submitted, the string of name/value pairs is transmitted to the server and made available to the page named in the form's ACTION parameter. That target page has access to the form data through the Request Object's Form Collection. Any scripts on the page can access these form values through the reference: Request.Form("fieldName").

 

Let's consider how to code a script on the welcome.asp page to check the information transmitted from the logon.asp page. We'll assume for the present example that we only need to check that the submitted password is "xyzzy." If users do not enter this value, then they do not get to see the page. Rather, they will be redirected back to the logon.asp page. If they submit the correct password, the page will display.

Our script needs to be at the top of the welcome.asp page so that it can evaluate the password before the page is revealed in the browser. You always need to keep in mind that the location of a script depends in large measure on when it is to be run. So, place it on the page where its processing is required.

In order to check the password, the VBScipt coding uses an If statement. If the password is incorrect, the user is immediately redirected back to the logon.asp page. If the password is correct, the user does not get redirected and the welcome.asp page is displayed. Here is the coding for the complete page:

welcome.asp

 

<%
If Request.Form("Password") <> "xyzzy" Then
  Response.Redirect("logon.asp")
End If
%>

<html>
<body>
<h3>Welcome Page</h3>
<p>Welcome to my page.</p>
</body>
</html>

Accessing the Request.Form Collection

Recall that data submitted from a form are placed into the Request.Form Collection, and that the values from the form fields can be accessed through the reference Request.Form("fieldName"). Therefore, the script references Request.Form("Password") to check the password value that was entered on the form and transmitted to the server:

If, as evaluated here, the Password value is not "xyzzy", then the user is redirected to the logon.asp page with the statement Response.Redirect("logon.asp"). If, on the other hand, the value submitted is "xyzzy," then the redirection doesn't take place. The script ends and this welcome.asp page is sent to the user's browser. Note that the value "xyzzy" is enclosed in quotation marks, indicating that this is a text string. Keep in mind that ALL values in an HTML form are text strings. Even if you have a field into which numbers are entered, the numerals are still considered to be text strings. You can perform arithmetic using these numerals; however, they need to be converted from strings to numbers before doing so. More about this later.

 

The Response.Redirect() Method

Recall, the ASP Response Object contains properties and methods that generally deal with output from server processing. The Response.Write() method, for example, has been used to write server variables, text, and HTML directly to a Web page. This object also supplies a Redirect() method that is used to transfer script control directly and immediate to a different page. Its general format is shown below.

Response.Redirect("url")

This redirection is exactly what we want to happen if the user types the incorrect password. So, the code

Response.Redirect("logon.asp")

transfers script control directly to the logon.asp page if the user has submitted the incorrect password. Thus, the user doesn't get an opportunity to see the welcome.asp page. Before the server finishes processing the welcome.asp page and sending it to the user in response to the action="welcome.asp" URL request that was coded on the form, the script interrupts and directs the server to access the logon.asp page and send it to the user instead.

Viewing the Page Source

 

You might be wondering why we would code a password directly on a Web page. Wouldn't it be seen by someone who looks at the code listing through the browser's "Vew Source" menu? No, it is not revealed. Remember that the server intercepts .asp pages and does not immediately send them back to the browser making the URL request. First, the server runs the page through its ASP processor. It looks for VBScript code and executes that code, all the while recreating a purely HTML version of the page to be sent back to the user. Users never receives and never get to see any code on the pages transmitted back to the browser. They only get to view the results of processing--not the processing instructions themselves. Therefore, it is perfectly safe to include passwords or other private information within a script. This is not to say that this is the best way to check passwords; but it's a sufficient start.

 

Directory Structure

Before we begin, let's take care of some administrative chores ourselves. We will be creating several pages that, generally, have to do with maintaining a database, and later with running an eCommerce site for selling products on the Web. In order to better organize the Web pages, databases, and other resources for these applications, we'll set up the following directory structure. d:\eCommerce (Folder)
  Databases (Folder)
  Pictures (Folder)

We'll create a root directory named eCommerce and assume it is located on the Web server at d:\eCommerce. Shortly, we'll be designing a database of products and gathering product pictures to display on the site, so we'll create a couple of subdirectories named Databases and Pictures. All of the Web pages that we produce will be placed in the main eCommerce folder.

An Administrative Menu

To make our task as database administrators a little easier, we'll also create a menu of links to the various pages. In that way we'll be able to test our system by clicking through the menu rather than entering URL's into the browser.


The tutorial menu on the left contains links to the eCommerce site we are building. The link labeled Database Maintenance Site at the bottom of the menu is the entry to the site administration pages, starting with this administrative menu. The site opens in a separate window so that you can view it and these tutorial pages at the same time. You can view the menu page described here by clicking on that link.


Coding the admin.asp Page

The database administration menu page is password protected. As database administrator you should have private access to routines to maintain your data. You can do this by coding a form on the menu page that requires entry of a password prior to display of the link items. (The password for the example application has already been entered into the field when the page appears. This is to save you from having to remember another password. The password is "xyzzy".)

After you have entered the correct password, the menu of links appears. Coding for this admin.asp page is shown below:

admin.asp

 

<%
If Request.Form("SubmitButton")="Logon" Then
  If Request.Form("Password")="xyzzy" Then
    Session("Password")="OK"
  End If
End If

If Request.Form("Submit")="Logoff" Then
  Session("Password")=""
End If
%>

<html>
<body>

<h3>eCommerce database - Administration Menu</h3>

<% If Session("Password")<>"OK" Then %>

  <form action="admin.asp" method="post">
    Password: <input type="password" name="Password" size="10">
    <input type="submit" name="SubmitButton" value="Logon">
  </form>

<% Else %>

  <table border="1" cellpadding="3">
  <tr>
    <td><a href="display.asp">display.asp</a></td>
    <td>Display records in database</td>
  </tr>
  <tr>
    <td><a href="add.asp">add.asp</a></td>
    <td>Add records to database</td>
  </tr>
  <tr>
    <td><a href="change.asp">change.asp</a></td>
    <td>Change records in database</td>
  </tr>
  <tr>
    <td><a href="delete.asp">delete.asp</a></td>
    <td>Delete records from database</td>
  </tr>
  </table>
  <br>
  <form action="admin.asp" method="post">
    <input type="submit" name="Submit" value="Logoff">
  </form>

<% End If %>

</body>
</html>

The first item to notice is the script at the top of the page. This script is activated when the password form is submitted. The script checks to see if the submitted password is "xyzzy". If so, then a Session variable named Password is set to "OK" indicating that you have entered the correct password. This Session variable will remain in effect until you exit your browser (or unless you get called away to the phone for more than 20 minutes).

The second part of this script handles logging off the site. When the "Logoff" button is clicked, this script resets the Session("Password") variable to null ("").

You'll need to remember to create a global Session variable named Session("Password") within the Session_OnStart subroutine of your global.asa file. It's initial value can be set to "" (null) to establish the variable. Also, remember to place the global.asp file within your root directory. Even though your database maintenance pages will appear in your eCommerce directory, the global.asa file for the site--and for any other sites you create--must appear in your root directory.

The body of the document is composed of two HTML sections coded within a VBScript condition test. The first line of the condition test is If Session("Password")<>"OK"

If you have not yet entered the proper password, the Session("Password") variable is not "OK" and the form will appear to permit you to enter the password. Otherwise, if you have already entered the password and the Session("Password") variable is set to "OK", then (the form is not displayed and) the table of menu items is displayed. Following the menu is the "Logoff" button. Once you have logged on with the correct password, you are free to come and go from this page as many times as you need, so long as your Session does not time out.

Style Sheets

In these tutorials we emphasize the scripting and downplay the HTML coding. This is so we do not get distracted from the main points. Still, as you create your pages, you might wish to give more consideration to the look of your pages. It will be good practice to include stylesheets for your pages and experiment with various layouts and styles. The example pages shown in this tutorial have a stylesheet applied. We will not be discussing this stylesheet, but it is displayed below and is linked to from each of the database administration pages. stylesheet.css

body {
  margin:15px;
  background-color:gainsboro;
  font-family:arial;
  font-size:9pt;
  }

td {
  font-family:arial;
  font-size:9pt;
  }

th {
  font-family:arial;
  font-size:9pt;
  font-style:italic;
  text-align:center;
  background-color:steelblue;
  color:white;
  }

.small {
  font-family:arial;
  font-size:8pt;
  color:red;
  }

.head1 {
  font-family:times new roman;
  font-size:14pt;
  font-weight:bold;
  color:steelblue;
  }

.head2 {
  font-family:times new roman;
  font-size:12pt;
  font-weight:bold;
  color:steelblue;
  }

a:link, a:active, a:visited {
  text-decoration:none;
  color:steelblue;
  }

a:hover {
  text-decoration:underline;
  color:red;
  }

.button {
  width:100px;
  text-align:center;
  font-family:arial;
  font-size:9pt;
  background-color:steelblue;
  color:white;
  }

The buttons that appear on the forms deserve special mention. You'll notice that they change color when the mouse hovers over them and that the cursor changes into a hand icon.

This effect is accomplished through application of Dynamic HTML (DHTML), using various styles triggered by JavaScript code. The stylesheet class applied to the button is given in the above stylesheet under the class name .button. This style sets the button's original appearance and is applied to the above button with the following code: <input type="submit" name="Button" class="button" value="Click Me">

In order for the button to change colors and to display the hand icon, two JavaScript functions are needed. The first function, named ChangeOver() changes the button's color and changes the icon when the cursor is moved over the button. The second function, named ChangeOut(), returns the button's appearance to its normal state. These functions are activited by two event handlers coded in the button's <INPUT> tag: <input type="submit" name="Button" class="button" value="Click Me"
   onMouseOver="ChangeOver(this)"; onMouseOut="ChangeOut(this)" >

The onMouseOver="ChangeOver(this)" event handler calls the function ChangeOver(button) when the cursor is on top of the button. The onMouseOut="ChangeOut(this)" event handler triggers the function ChangeOut(button) when the cursor is removed from over the button. Both of these function calls pass a self-reference (this) to the button containing these event handlers to the functions, where this reference is received through the argument (button). These functions handle the color and cursor changes for the referenced button.. The JavaScript script appearing (anywhere) on the page is the following:

<script language="javascript">
function ChangeOver(button)
{
  button.style.backgroundColor='lightsteelblue'
  button.style.color='black'
  button.style.cursor='hand'
}
function ChangeOut(button)
{
  button.style.backgroundColor='steelblue'
  button.style.color='white'
  button.style.color='default'
}
</script>

You can experiment with your own stylesheet and JavaScript functions to bring the look you want to your pages.

 

DB Maintenance

Now that we have a database full of products we can begin preparing the administrative pages to maintain that information and keep it up to date. One of the functions we'll need to perform is to produce listings of the items in the Products table. We'll start off with a simple display of all products and then modify the selection as we work through this tutorial.

The first page we'll code is a complete product listing.

This display is an HTML table containing all records and all fields from the Products table of the eCommerce.mdb database. You can image the work involved if you had to hard-code this information within the table. Fortunately, with ASP it involves very little coding to display 25 records, or even hundreds of records, within a table structure.

The page begins with a heading and a link back to the administrative menu. Then comes the HTML coding for the table headings.

<html>
<body>

<h1>eCommerce database - Product Listing 1</h1>
<a href="admin.asp">Back to Menu</a>

<table border="1">
<tr>
  <th>ItemNumber</th>
  <th>ItemType</th>
  <th>ItemProducer</th>
  <th>ItemTitle</th>
  <th>ItemDescription</th>
  <th>ItemPrice</th>
  <th>ItemQuantity</th>
  <th>Picture</th>
<tr>

This listing doesn't show it, but a stylesheet has been used to set font faces, sizes, colors, and other formatting styles. Again, we'll not complicate the listings with these styles and tags so you can concentrate on the main code.

The row of table headings is hard-coded in HTML since it does not change, irrespective of the number of records displayed in the table. Next, though, come the table rows containing product information. There can be any number of products and any number of rows. It all depends on how many records there are in the Products table.

It is time, then, to open the eCommerce.mdb database and extract a recordset comprised of all records in the Products table. Next on the page, then, comes a script to make that connection and to create that recordset.

<%
Set CNObj=Server.CreateObject("ADODB.Connection")
CNObj.Open "DBQ=d:\eCommerce\Databases\eCommerce.mdb;DRIVER=Microsoft Access Driver (*.mdb)"
Set RSDisplay=Server.CreateObject("ADODB.Recordset")
SQL="SELECT * FROM Products ORDER BY ItemNumber"
RSDisplay.Open SQL,CNObj


A Connection Object is created and its Open method is used to connect to our database. You'll need to make sure that the DBQ path to your database is coded correctly. Don't use this example.

Following the opening of the eCommerce.mdb database, the script creates a Recordset Object in order to extract records from the Products table. An object named RSDisplay is created. We can now use the RSDisplay object's Open method to extract a set of records. We could, as we've done before, open the entire Products table using the syntax: RSDisplay.Open "Products",CNObj. However, we want the records to be displayed in ItemNumber sequence, so we'll use an SQL statement to do this. By issuing the statement SELECT * FROM Products ORDER BY ItemNumber, we retrieve all records and all fields, plus the records are arranged in sequence.

Our RSDisplay recordset is an in-memory duplicate of the Products table, with the recordset cursor pointing to the first record. We need, then, to set up a program loop to step through the recordset a record at a time and display the value in each of the record's data fields. We reference the data values through the recordset's Fields Collection. The syntax, you will recall, is RSDisplay.Fields("FieldName")

Each record is displayed as a row in the table we began coding above. Therefore, inside this program loop we need to define a table row. Plus, each table cell along the row contains one of the fields in the record--an item from the RSDisplay.Fields Collection.

Do While Not RSDisplay.EOF %>
  <tr valign="top">
    <td><%=RSDisplay.Fields("ItemNumber")%></td>
    <td><%=RSDisplay.Fields("ItemType")%></td>
    <td><%=RSDisplay.Fields("ItemProducer")%></td>
    <td><%=RSDisplay.Fields("ItemTitle")%></td>
    <td><%=RSDisplay.Fields("ItemDescription")%></td>
    <td align="right"><%=RSDisplay.Fields("ItemPrice")%></td>
    <td align="right"><%=RSDisplay.Fields("ItemQuantity")%></td>
    <td><img src="Pictures/<%=RSDisplay.Fields("ItemNumber")%>.jpg" width="50"></td>
  </tr>
  <% RSDisplay.MoveNext
Loop

Our script provides the HTML coding for a single table row, with each cell displaying the value of one of the fields from the RSDisplay.Fields Collection. This table row, though, appears inside a program loop that iterates through all of the records in the recordset. Thus, a table row will be formatted for each record. You describe one row in your coding and the script makes 25 such rows when it runs! It's interesting to look at the source code in your browser. Do this from the display1.asp page and you will see the HTML for the entire table with all of the data values inserted. Then, think about trying to hard-code this by hand.

Displaying the pictures associated with the products presents interesting coding. Within the last table cell on a row there appears an <IMG> tag necessary to display an image. Check the SRC attribute coding. We know that the pictures are in the Pictures folder, and we know that all of the picture files end with the .jpg suffix. Since the picture file name matches the item number of the related product, we can have the script simply insert the matching ItemNumber value into the SCR string to compose the proper URL for finding a matching picture. Pretty slick. Notice that we've resized the image from its original width to better fit within the table cell.

All that remains is to close things down. We'll formally close the Recordset and Connection Objects and place the closing </TABLE> tag on the end of the table. Our page is done.

RSDisplay.Close
CNObj.Close
%>
</table>

</body>
</html>

Just so you can see the page in its entirety, it is reproduced below: display1.asp

<html>
<body>

<h1>eCommerce database - Product Listing 1</h1>
<a href="admin.asp">Back to Menu</a>

<table border="1">
<tr>
  <th>ItemNumber</th>
  <th>ItemType</th>
  <th>ItemProducer</th>
  <th>ItemTitle</th>
  <th>ItemDescription</th>
  <th>ItemPrice</th>
  <th>ItemQuantity</th>
  <th>Picture</th>
<tr>

<%
Set CNObj=Server.CreateObject("ADODB.Connection")
CNObj.Open "DBQ=d:\eCommerce\Databases\eCommerce.mdb;DRIVER=Microsoft Access Driver (*.mdb)"
Set RSDisplay=Server.CreateObject("ADODB.Recordset")
SQL="SELECT * FROM Products ORDER BY ItemNumber"
RSDisplay.Open SQL,CNObj

Do While Not RSDisplay.EOF %>
  <tr valign="top">
    <td><%=RSDisplay.Fields("ItemNumber")%></td>
    <td><%=RSDisplay.Fields("ItemType")%></td>
    <td><%=RSDisplay.Fields("ItemProducer")%></td>
    <td><%=RSDisplay.Fields("ItemTitle")%></td>
    <td><%=RSDisplay.Fields("ItemDescription")%></td>
    <td align="right"><%=RSDisplay.Fields("ItemPrice")%></td>
    <td align="right"><%=RSDisplay.Fields("ItemQuantity")%></td>
    <td><img src="Pictures/<%=RSDisplay.Fields("ItemNumber")%>.jpg" width="50"></td>
  </tr>
  <% RSDisplay.MoveNext
Loop

RSDisplay.Close
CNObj.Close
%>
</table>

</body>
</html>

 

Viewing Folders and Files

The ASP Scripting Object is your access to the server's directory structure. Through various objects comprising this component scripts can manipulate folders and files in much the same way as you can through the Windows Desktop and Windows Explorer. That is, you can view the contents of drives, create folders and files, view the contents of folders, and move and copy folders and files.

The FileSystemObject

All access to the server's directory structure is through the FileSystemObject. This object is instantiated in a script by using the Server Object's CreateObject method.

Set FileSystemObject = Server.CreateObject("Scripting.FileSystemObject")

You simply need to create a FileSystemObject name to which the FileSystemObject is assigned. For example, Set FSObj = Server.CreateObject("Scripting.FileSystemObject")

creates an object named FSObj through which you have access to all the properties and methods necessary to work with the server's directory structure.

The Folder Object

A FileSystemObject contains several methods through which you can view and manipulate folders. One of these is the GetFolder() method, which creates a Folder Object to identify the particular folder within which you wish to work. The general format for creating a Folder Object is

Set FolderObject = FileSystemObject("path to folder")

The FileSystemObject is a reference to a previously created FileSystemObject, the "path to folder" is the server's physical path (beginning with the drive letter) to a particular folder, and FolderObject is a name you supply for accessing the identified folder. Thus, by creating a FileSystemObject and, through it, a Folder Object, you indicate which folder you want to work in. The following example provides script access to our eCommerce folder located on the server's d: drive. Set FSObj = Server.CreateObject("Scripting.FileSystemObject")
Set FolderObj = FSObj.GetFolder("d:\eCommerce")

The SubFolders Collection

Folder Objects contain two collections needed for viewing the contents of folders. The SubFolders Collection is a list of all the subfolders in an identified folder; this collection is made available through the SubFolders property of the Folder Object. The Files Collection (see below) is a list of all files contain in an identified folder. Let's write a short script to view all of the subfolders in the eCommerce folder.

<%
Set FSObj = Server.CreateObject("Scripting.FileSystemObject")
Set FolderObj = FSObj.GetFolder("d:\eCommerce")

For Each Item in FolderObj.SubFolders
  Response.Write(Item & "<br>")
Next
%>

When this script is run the following output is produced:

D:\eCommerce\Databases
D:\eCommerce\Pictures

A FileSystemObject named FSObj is created through which its GetFolder() method is used to create a Folder Object named FolderObj. This Folder Object contains a collection of subfolders referenced by its SubFolders property. We use the special For Each...Next loop to iterate through the items in this collection. Variable Item takes on the values of the individual subfolder paths that comprise the collection, and we write these on separate output lines. Note that the items in the collection are full path names.

The Files Collection

The second collection provided by the Folder Object is the Files Collection. This collection is a list of all files contain in an identified folder. Let's write a script to view all of the files in the eCommerce folder.

<%
Set FSObj = Server.CreateObject("Scripting.FileSystemObject")
Set FolderObj = FSObj.GetFolder("d:\eCommerce")

For Each Item in FolderObj.Files
  Response.Write(Item & "<br>")
Next
%>

When this script is run the following output is produced. You should recognize the ASP pages that have been created for the database maintenance applications.

D:\eCommerce\add1.asp
D:\eCommerce\add2.asp
D:\eCommerce\add3.asp
D:\eCommerce\add4.asp
D:\eCommerce\admin.asp
D:\eCommerce\change.asp
D:\eCommerce\delete.asp
D:\eCommerce\display1.asp
D:\eCommerce\display2.asp
D:\eCommerce\display3.asp
D:\eCommerce\display4.asp

The script is almost identical to the one used to list all subfolders in a folder. This only difference is the reference to the FolderObj.Files property of the Folder Object.

File Properties

The Files Collection contains references to all of the files within a subfolder. These references are actually to the File Object associated with each of the files. As such, these File Objects contain their own set of properties which characterizes the files in the collection. The following table is produced by a script which lists the files in the eCommerce folder along with some of these properties.

Now that you've gotten free know-how on this topic, try to grow your skills even faster with online video training. Then finally, put these skills to the test and make a name for yourself by offering these skills to others by becoming a freelancer. There are literally 2000+ new projects that are posted every single freakin' day, no lie!


Previous Article

Next Article


Sucheta's Comment
i want some asp.net tutorials, can you please provide such stuff thanks
03 Thu May 2012
Admin's Reply:

We'll try our best.




Audel's Comment
And to think I was going to talk to smnoeoe in person about this.
05 Thu Jan 2012
Admin's Reply:

well Audell Glad we help you out.




pickatutorial.com's Comment
Thanks for such useful stuff.
05 Tue Oct 2010
Admin's Reply:

You're very welcome




Prasanna's Comment
GREAT. I CAN'T TELL ABOUT THIS, NO WORDS.
04 Fri Dec 2009
Admin's Reply: I'm glad you liked it.





Facebook