Home > Articles > Programming > Visual Basic

  • Print
  • + Share This
Like this article? We recommend

The Embedded HTML Problem

ASP files enable developers to mix UI code (HTML) with logic code (VBScript), which leads to maintenance problems. Of course, VB doesn't allow you to include HTML code at all, so the only way to send HTML to the browser is by typing gAspResp.Write statements. At first reading, this might sound even worse than using ASP files.

One solution to the embedded HTML problem is based on the following facts:

  • An HTML file is a simple ASCII text file.

  • VB can easily read the contents of an ASCII text into a string variable.

  • String variables can easily be manipulated using VB's intrinsic functions.

So, rather than using hundreds of gAspResp.Write statements to send HTML, write a procedure that reads a file containing the HTML code into a string variable, and then use gAspResp.Write to send that variable's contents to the Web browser.

To illustrate, create a simple HTML file named HelloWorld.htm that contains something similar to this:

<p><b><font size="4">Hello World!</font></b></p>

Save this file in the same folder as the rest of your project files.

Next, write a general-purpose function that reads the contents of a text file into a string variable. Consider this example:

Private Function LoadHTML(ByVal lFileName As String) As String
    Dim lFileNbr  As Integer
    On Error GoTo ErrHandler
    lFileNbr = FreeFile
    Open App.Path & "\" & lFileName For Input Access Read As #lFileNbr
    LoadHTML = Input(LOF(lFileNbr), lFileNbr)
    Close #lFileNbr
    Exit Function
    Call Err.Raise(vbObjectError, "clsWebApp", "Can't load html file " & lFileName)
End Function

Note that this function uses App.Path and therefore assumes that the HTML file will be found in the same folder as the VB project file (or the DLL file, when compiled).

Now modify the WebMain procedure to send the HelloWord.htm file:

Public Sub WebMain()
    Dim lHTML As String
    lHTML = LoadHTML("HelloWorld.htm")
    Call gAspResp.Write(lHTML)
End Sub

Run and test your application, as was done before, to make sure that the HTML file is now being sent.

This technique solves the embedded HTML problem by completely separating the app's UI code from its logic, and it again enables you to use your favorite WYSIWIG Web UI design tool. In fact, a completely different person than the one writing the supporting logic can develop the UI for a Web application. This is important because code developers and UI developers often have different skill sets. The code developer and the HTML author need to agree on only the HTML filenames.

  • + Share This
  • 🔖 Save To Your Account