Lesson 8 | Response.Write |
Objective | Write ASP variables, text and HTML code to send to a browser. |
ASP Page Responds to Browser Request
When a Web server sends data to a browser, it is sent as a series of data bytes.
Response.Write()
lets you insert values from ASP scripts (as HTTP code) as they are created.
So far, we have seen examples of writing:
- Values of variables and constants
- Text strings (as literals and as the result of an
If/Else
statement)
- Results of calculations and functions
As you will recall, the browser never sees any ASP code that is a part of the output, because it is evaluated and replaced before being sent by the server.
Concatenating Strings
Concatenation is the process of merging two strings into one. In VBScript, the concatenation operator is the ampersand (&
).
Here are examples of how concatenation works and how it can be used with Response.Write
:
strResult = "Hello, " & "World"
would result in strResult
containing the value "Hello, World"
strFirst = "Hello,"
strSecond = "World"
strResult = strFirst & strSecond
would result in strResult
also containing the value "Hello, World"
<% Response.Write(strFirst & strSecond)%>
would cause "Hello World"
to be displayed on the user's browser.
In the above examples, both of the expressions are of the String subtype. Whenever an expression used in this way is not a string, ASP will convert it to a String subtype.
Writing HTML tags with Response.Write()
You can use Response.Write()
to output HTML, in addition to values of ASP variables. For example, you could write:
<% Response.Write("<TABLE WIDTH='100%'>") %>
In standard HTML the sequence for the table width (<TABLE WIDTH=90%>
) includes the characters %>
.
Since those characters are used by ASP as an ending delimiter, we cannot use them directly, but must signal the interpreter using a back slash (\
), like this:
<% Response.Write("<TABLE WIDTH=90%\>") %>
The preferred method is the first example, which avoids the issue altogether.
Question: If you have a variable strCity containing "Boston" and a variable strState containin "MA", how could you use a
Response.Write statement to display the values of the two variables as "Boston, MA"?
Answer:
<% Response.Write(strCity & *,* strState) %>
Response.Write concatenates string variables with a literal.
Question:
If you have a variable strLength containing the length of a rectangle and variable strWidth variable containing the
rectangle's width, can you write a single Response.Write statement that would display the length and width of a rectangle and its perimeter
without creating a separate variable to hold the calculate perimeter value?
Answer:
Yes, Response.Write
can display a result that is calculated in the Response.Write
statement .
Your statement would like this:
<% Response.Write "Length: " & intLength & " Width: " & intWidth
& "Perimeter: " & ( 2*intLength + 2*intWidth) %>
The next lesson describes the three parts of ASP technology.