How to Format Conditional Output in Classic ASP
This example is for an existing Classic ASP application. It combines three common operations by selecting a message, joining its parts and displaying the server's current date and time. The script runs on IIS. It does not use the visitor's clock.
Create the page
Save this as message.asp in a Classic ASP-enabled test application, then request it through IIS.
<%@ Language="VBScript" %>
<% Option Explicit %>
<%
Dim requestedName, greeting, currentTime
requestedName = CStr(Request.QueryString("name"))
currentTime = Now()
If Len(requestedName) = 0 Then
greeting = "Hello, visitor"
ElseIf Len(requestedName) > 80 Then
greeting = "Hello, your supplied name is too long"
Else
greeting = "Hello, " & requestedName
End If
Response.Write "<p>" & Server.HTMLEncode(greeting) & "</p>"
Response.Write "<p>Server time: " & _
Server.HTMLEncode(CStr(currentTime)) & "</p>"
%>
Open message.asp?name=Sam. The page displays Hello, Sam and a server-time value. Open it without a name to exercise the first branch. A value longer than 80 characters exercises the second branch.
Keep values separate from markup
Use & for string concatenation. A space followed by _ continues the expression onto the next physical line. Now() returns a date value. CStr formats it using the server's locale. This is suitable for a simple display, but it is not a stable interchange format or an explicit UTC timestamp.
HTML-encode the completed message when placing it in HTML text. For example, the name <em>Sam</em> should appear as text instead of becoming an element. Encoding for HTML text is not a replacement for JavaScript, URL or SQL-specific handling in other contexts.
Avoid common mistakes
Use straight quotes in source files. ElseIf is one word, and block-form conditionals end with End If. MsgBox is a script-host dialog. It is not how a server-side ASP page sends a message to a browser. Use Response.Write for the HTTP response.
References


Author: Herman Schoenfeld