Friday, November 30, 2007

Calling a function from .aspx

There are times when programming web applications where a control just doesn't offer the functionality that one may be seeking. Perhaps dynamically generated JavaScript, HTML, or other code needs to be added to a page, but needs to be kept separate from a label.

Insert the following tag into your .aspx page.

  • <%= FunctionName() %>
In the .aspx.vb file associated with that page add:
  • Public Function FunctionName()
    'Include any logic here
    Return "Hello World!"
    End Function
Doing this hides the fact that logic was used to dish out the content.

Variables can be build into the function to return different results. For example:
  • <%= FunctionName("Hello") %>
    • Returns: Hello World!
      which looks like this in the page source: Hello World!
  • <%= FunctionName("GoodBye") %>
    • Returns: Good Bye World!
      which looks like this in the page source: Good Bye World!
  • Public Function FunctionName(ByVal strSomeVariable As String)

    'Declare a variable to hold the html
    Dim strReturnHTML As String

    'Include any logic here
    If strSomeVariable = "Hello" Then
    strReturnHTML = "Hello World!"
    ElseIf strSomeVariable = "GoodBye" Then
    strReturnHTML = "Good Bye World!"
    Else
    strReturnHTML = "error: no parameter was set"
    End If

    Return strReturnHTML



    End Function

No comments: