"
 
 
 
ASP.NET (snapshot 2017) Microsoft documentation and samples

Introduction to ASP.NET Web Programming Using the Razor Syntax (Visual Basic)

by Tom FitzMacken

This article gives you an overview of programming with ASP.NET Web Pages using the Razor syntax and Visual Basic. ASP.NET is Microsoft’s technology for running dynamic web pages on web servers.

What you’ll learn:

  • The top 8 programming tips for getting started with programming ASP.NET Web Pages using Razor syntax.
  • Basic programming concepts you’ll need.
  • What ASP.NET server code and the Razor syntax is all about.

Software versions

  • ASP.NET Web Pages (Razor) 3

This tutorial also works with ASP.NET Web Pages 2.

Most examples of using ASP.NET Web Pages with Razor syntax use C#. But the Razor syntax also supports Visual Basic. To program an ASP.NET web page in Visual Basic, you create a web page with a .vbhtml filename extension, and then add Visual Basic code. This article gives you an overview of working with the Visual Basic language and syntax to create ASP.NET Webpages.

[!NOTE] The default website templates for Microsoft WebMatrix (Bakery, Photo Gallery, and Starter Site, etc.) are available in C# and Visual Basic versions. You can install the Visual Basic templates by as NuGet packages. Website templates are installed in the root folder of your site in a folder named Microsoft Templates.

The Top 8 Programming Tips

This section lists a few tips that you absolutely need to know as you start writing ASP.NET server code using the Razor syntax.

1. You add code to a page using the @ character

The @ character starts inline expressions, single-statement blocks, and multi-statement blocks:

[!code-vbhtmlMain]

   1:  <!-- Single statement blocks  -->
   2:  @Code  Dim total = 7  End Code
   3:  @Code  Dim myMessage = "Hello World" End Code
   4:   
   5:  <!-- Inline expressions -->
   6:  <p>The value of your account is: @total </p>
   7:  <p>The value of myMessage is: @myMessage</p>        
   8:      
   9:  <!-- Multi-statement block -->    
  10:  @Code 
  11:      Dim greeting = "Welcome to our site!"
  12:      Dim weekDay = DateTime.Now.DayOfWeek
  13:      Dim greetingMessage = greeting & " Today is: " & weekDay.ToString()
  14:  End Code 
  15:  <p>The greeting is: @greetingMessage</p>

The result displayed in a browser:

Razor-Img1
Razor-Img1

[!TIP]

HTML Encoding

When you display content in a page using the @ character, as in the preceding examples, ASP.NET HTML-encodes the output. This replaces reserved HTML characters (such as < and > and &) with codes that enable the characters to be displayed as characters in a web page instead of being interpreted as HTML tags or entities. Without HTML encoding, the output from your server code might not display correctly, and could expose a page to security risks.

If your goal is to output HTML markup that renders tags as markup (for example <p></p> for a paragraph or <em></em> to emphasize text), see the section Combining Text, Markup, and Code in Code Blocks later in this article.

You can read more about HTML encoding in Working with HTML Forms in ASP.NET Web Pages Sites.

2. You enclose code blocks with Code…End Code

A code block includes one or more code statements and is enclosed with the keywords Code and End Code. Place the opening Code keyword immediately after the @ character — there can’t be whitespace between them.

[!code-vbhtmlMain]

   1:  <!-- Single statement block.  -->
   2:  @Code
   3:      Dim theMonth = DateTime.Now.Month
   4:  End Code
   5:  <p>The numeric value of the current month: @theMonth</p>
   6:   
   7:  <!-- Multi-statement block. -->
   8:  @Code
   9:      Dim outsideTemp = 79
  10:      Dim weatherMessage = "Hello, it is " & outsideTemp & " degrees."
  11:  End Code 
  12:  <p>Today's weather: @weatherMessage</p>

The result displayed in a browser:

Razor-Img2
Razor-Img2

3. Inside a block, you end each code statement with a line break

In a Visual Basic code block, each statement ends with a line break. (Later in the article you’ll see a way to wrap a long code statement into multiple lines if needed.)

[!code-vbhtmlMain]

   1:  <!-- Single statement block. -->
   2:  @Code
   3:      Dim theMonth = DateTime.Now.Month
   4:  End Code
   5:   
   6:  <!-- Multi-statement block. -->
   7:  @Code
   8:      Dim outsideTemp = 79
   9:      Dim weatherMessage = "Hello, it is " & outsideTemp & " degrees."
  10:  End Code 
  11:   
  12:  <!-- An inline expression, so no line break needed. -->
  13:  <p>Today's weather: @weatherMessage</p>

4. You use variables to store values

You can store values in a variable, including strings, numbers, and dates, etc. You create a new variable using the Dim keyword. You can insert variable values directly in a page using @.

[!code-vbhtmlMain]

   1:  <!-- Storing a string -->
   2:  @Code 
   3:      Dim welcomeMessage = "Welcome, new members!"
   4:  End Code
   5:  <p>@welcomeMessage</p>
   6:      
   7:  <!-- Storing a date -->
   8:  @Code 
   9:      Dim year = DateTime.Now.Year
  10:  End Code
  11:   
  12:  <!-- Displaying a variable -->
  13:  <p>Welcome to our new members who joined in @year!</p>

The result displayed in a browser:

Razor-Img3
Razor-Img3

5. You enclose literal string values in double quotation marks

A string is a sequence of characters that are treated as text. To specify a string, you enclose it in double quotation marks:

[!code-vbhtmlMain]

   1:  @Code 
   2:      Dim myString = "This is a string literal"
   3:  End Code

To embed double quotation marks within a string value, insert two double quotation mark characters. If you want the double quotation character to appear once in the page output, enter it as "" within the quoted string, and if you want it to appear twice, enter it as """" within the quoted string.

[!code-vbhtmlMain]

   1:  <!-- Embedding double quotation marks in a string -->
   2:  @Code 
   3:      Dim myQuote = "The person said: ""Hello, today is Monday."""
   4:  End Code
   5:  <p>@myQuote</p>

The result displayed in a browser:

Razor-Img4
Razor-Img4

6. Visual Basic code is not case sensitive

The Visual Basic language is not case sensitive. Programming keywords (like Dim, If, and True) and variable names (like myString, or subTotal) can be written in any case.

The following lines of code assign a value to the variable lastname using a lowercase name, and then output the variable value to the page using an uppercase name.

[!code-vbhtmlMain]

   1:  @Code 
   2:      Dim lastName = "Smith"
   3:      ' Keywords like dim are also not case sensitive.
   4:      DIM someNumber = 7
   5:  End Code
   6:  <p>The value of the <code>lastName</code> variable is: @LASTNAME</p>

The result displayed in a browser:

vb-syntax-5
vb-syntax-5

7. Much of your coding involves working with objects

An object represents a thing that you can program with — a page, a text box, a file, an image, a web request, an email message, a customer record (database row), etc. Objects have properties that describe their characteristics — a text box object has a Text property, a request object has a Url property, an email message has a From property, and a customer object has a FirstName property. Objects also have methods that are the “verbs” they can perform. Examples include a file object’s Save method, an image object’s Rotate method, and an email object’s Send method.

You’ll often work with the Request object, which gives you information like the values of form fields on the page (text boxes, etc.), what type of browser made the request, the URL of the page, the user identity, etc. This example shows how to access properties of the Request object and how to call the MapPath method of the Request object, which gives you the absolute path of the page on the server:

[!code-htmlMain]

   1:  <table border="1"> 
   2:      <tr>
   3:          <td>Requested URL</td>
   4:          <td>Relative Path</td>
   5:          <td>Full Path</td>
   6:          <td>HTTP Request Type</td>
   7:      </tr>
   8:      <tr>
   9:          <td>@Request.Url</td>
  10:          <td>@Request.FilePath</td>
  11:          <td>@Request.MapPath(Request.FilePath)</td>
  12:          <td>@Request.RequestType</td>
  13:      </tr>
  14:  </table>

The result displayed in a browser:

Razor-Img5
Razor-Img5

8. You can write code that makes decisions

A key feature of dynamic web pages is that you can determine what to do based on conditions. The most common way to do this is with the If statement (and optional Else statement).

[!code-vbhtmlMain]

   1:  @Code
   2:     Dim result = ""
   3:     If IsPost Then
   4:        result = "This page was posted using the Submit button."
   5:     Else
   6:        result = "This was the first request for this page."
   7:     End If
   8:  End Code
   9:  <!DOCTYPE html>
  10:  <html lang="en">
  11:      <head>
  12:          <meta charset="utf-8" />
  13:          <title>Write Code that Makes Decisions</title>
  14:      </head>
  15:  <body>
  16:      
  17:      <form method="POST" action="" >
  18:          <input type="Submit" name="Submit" value="Submit"/>
  19:          <p>@result</p>
  20:      </form>
  21:      
  22:  </body>
  23:  </html>

The statement If IsPost is a shorthand way of writing If IsPost = True. Along with If statements, there are a variety of ways to test conditions, repeat blocks of code, and so on, which are described later in this article.

The result displayed in a browser (after clicking Submit):

Razor-Img6
Razor-Img6

[!TIP]

HTTP GET and POST Methods and the IsPost Property

The protocol used for web pages (HTTP) supports a very limited number of methods (“verbs”) that are used to make requests to the server. The two most common ones are GET, which is used to read a page, and POST, which is used to submit a page. In general, the first time a user requests a page, the page is requested using GET. If the user fills in a form and then clicks Submit, the browser makes a POST request to the server.

In web programming, it’s often useful to know whether a page is being requested as a GET or as a POST so that you know how to process the page. In ASP.NET Web Pages, you can use the IsPost property to see whether a request is a GET or a POST. If the request is a POST, the IsPost property will return true, and you can do things like read the values of text boxes on a form. Many examples you’ll see show you how to process the page differently depending on the value of IsPost.

A Simple Code Example

This procedure shows you how to create a page that illustrates basic programming techniques. In the example, you create a page that lets users enter two numbers, then it adds them and displays the result.

  1. In your editor, create a new file and name it AddNumbers.vbhtml.
  2. Copy the following code and markup into the page, replacing anything already in the page.

    [!code-vbhtmlMain]

       1:  @Code
       2:      Dim total = 0
       3:      Dim totalMessage = ""
       4:      if IsPost Then
       5:          ' Retrieve the numbers that the user entered.
       6:          Dim num1 = Request("text1")
       7:          Dim num2 = Request("text2")
       8:          ' Convert the entered strings into integers numbers and add.
       9:          total = num1.AsInt() + num2.AsInt()
      10:          totalMessage = "Total = " & total
      11:      End If
      12:  End Code
      13:  <!DOCTYPE html>
      14:  <html lang="en">
      15:      <head>
      16:          <meta charset="utf-8" />
      17:          <title>Adding Numbers</title>
      18:          <style type="text/css">
      19:              body {background-color: beige; font-family: Verdana, Ariel; 
      20:                  margin: 50px;
      21:                  }
      22:              form {padding: 10px; border-style: solid; width: 250px;}
      23:          </style>
      24:      </head>
      25:  <body>
      26:      <p>Enter two whole numbers and click <strong>Add</strong> to display the result.</p>
      27:      <p></p>
      28:      <form action="" method="post">
      29:      <p><label for="text1">First Number:</label>
      30:      <input type="text" name="text1" />
      31:      </p>
      32:      <p><label for="text2">Second Number:</label>
      33:      <input type="text" name="text2" />
      34:      </p>
      35:      <p><input type="submit" value="Add" /></p>
      36:      </form>
      37:      <p>@totalMessage</p>
      38:  </body>
      39:  </html>

    Here are some things for you to note:

    • The @ character starts the first block of code in the page, and it precedes the totalMessage variable embedded near the bottom.
    • The block at the top of the page is enclosed in Code...End Code.
    • The variables total, num1, num2, and totalMessage store several numbers and a string.
    • The literal string value assigned to the totalMessage variable is in double quotation marks.
    • Because Visual Basic code is not case sensitive, when the totalMessage variable is used near the bottom of the page, its name only needs to match the spelling of the variable declaration at the top of the page. The casing doesn’t matter.
    • The expression num1.AsInt() + num2.AsInt() shows how to work with objects and methods. The AsInt method on each variable converts the string entered by a user to a whole number (an integer) that can be added.
    • The <form> tag includes a method="post" attribute. This specifies that when the user clicks Add, the page will be sent to the server using the HTTP POST method. When the page is submitted, the code If IsPost evaluates to true and the conditional code runs, displaying the result of adding the numbers.
  3. Save the page and run it in a browser. (Make sure the page is selected in the Files workspace before you run it.) Enter two whole numbers and then click the Add button.

    Razor-Img7
    Razor-Img7

Visual Basic Language and Syntax

Earlier you saw a basic example of how to create an ASP.NET web page, and how you can add server code to HTML markup. Here you’ll learn the basics of using Visual Basic to write ASP.NET server code using the Razor syntax — that is, the programming language rules.

If you’re experienced with programming (especially if you’ve used C, C++, C#, Visual Basic, or JavaScript), much of what you read here will be familiar. You’ll probably need to familiarize yourself only with how WebMatrix code is added to markup in .vbhtml files.

Combining text, markup, and code in code blocks

In server code blocks, you’ll often want to output text and markup to the page. If a server code block contains text that’s not code and that instead should be rendered as is, ASP.NET needs to be able to distinguish that text from code. There are several ways to do this.

Whitespace

Extra spaces in a statement (and outside of a string literal) don’t affect the statement:

[!code-vbhtmlMain]

   1:  @Code Dim personName =    "Smith"    End Code

Breaking long statements into multiple lines

You can break a long code statement into multiple lines by using the underscore character _ (which in Visual Basic is called the continuation character) after each line of code. To break a statement onto the next line, at the end of the line add a space and then the continuation character. Continue the statement on the next line. You can wrap statements onto as many lines as you need to improve readability. The following statements are the same:

[!code-vbhtmlMain]

   1:  @Code
   2:      Dim familyName _
   3:      =  "Smith" 
   4:  End Code
   5:   
   6:  @Code
   7:      Dim _
   8:      theName _
   9:      = _
  10:      "Smith"
  11:  End Code

However, you can’t wrap a line in the middle of a string literal. The following example doesn’t work:

[!code-vbhtmlMain]

   1:  @Code 
   2:      ' Doesn't work.
   3:      Dim test = "This is a long _
   4:        string"
   5:  End Code

To combine a long string that wraps to multiple lines like the above code, you would need to use the concatenation operator (&), which you’ll see later in this article.

Code comments

Comments let you leave notes for yourself or others. Razor syntax comments are prefixed with @* and end with *@.

[!code-cshtmlMain]

   1:  @* A single-line comment is added like this example. *@
   2:      
   3:  @*
   4:      This is a multiline code comment. 
   5:      It can continue for any number of lines.
   6:  *@

Within code blocks you can use the Razor syntax comments, or you can use ordinary Visual Basic comment character, which is a single quote (') prefixed to each line.

[!code-vbhtmlMain]

   1:  @Code
   2:      ' You can make comments in blocks by just using ' before each line.
   3:  End Code
   4:      
   5:  @Code
   6:      ' There is no multi-line comment character in Visual Basic. 
   7:      ' You use a ' before each line you want to comment. 
   8:  End Code

Variables

A variable is a named object that you use to store data. You can name variables anything, but the name must begin with an alphabetic character and it cannot contain whitespace or reserved characters. In Visual Basic, as you saw earlier, the case of the letters in a variable name doesn’t matter.

Variables and data types

A variable can have a specific data type, which indicates what kind of data is stored in the variable. You can have string variables that store string values (like “Hello world”), integer variables that store whole-number values (like 3 or 79), and date variables that store date values in a variety of formats (like 4/12/2012 or March 2009). And there are many other data types you can use.

However, you don’t have to specify a type for a variable. In most cases ASP.NET can figure out the type based on how the data in the variable is being used. (Occasionally you must specify a type; you’ll see examples where this is true.)

To declare a variable without specifying a type, use Dim plus the variable name (for instance, Dim myVar). To declare a variable with a type, use Dim plus the variable name, followed by As and then the type name (for instance, Dim myVar As String).

[!code-vbhtmlMain]

   1:  @Code
   2:      ' Assigning a string to a variable.
   3:      Dim greeting = "Welcome" 
   4:      
   5:      ' Assigning a number to a variable.
   6:      Dim theCount = 3
   7:      
   8:      ' Assigning an expression to a variable.
   9:      Dim monthlyTotal = theCount + 5
  10:      
  11:      ' Assigning a date value to a variable.
  12:      Dim today = DateTime.Today
  13:      
  14:      ' Assigning the current page's URL to a variable.
  15:      Dim myPath = Request.Url
  16:      
  17:      ' Declaring variables using explicit data types.
  18:      Dim name as String = "Joe"
  19:      Dim count as Integer = 5
  20:      Dim tomorrow as DateTime = DateTime.Now.AddDays(1)
  21:  End Code

The following example shows some inline expressions that use the variables in a web page.

[!code-vbhtmlMain]

   1:  @Code
   2:      ' Embedding the value of a variable into HTML markup.
   3:      ' Precede the markup with @ because we are in a code block.
   4:      @<p>@greeting, friends!</p>
   5:  End Code
   6:   
   7:  <!-- Using a variable with an inline expression in HTML. --> 
   8:  <p>The predicted annual total is: @( monthlyTotal * 12)</p>
   9:   
  10:  <!--  Displaying the page URL with a variable. --> 
  11:  <p>The URL to this page is:  @myPath</p>

The result displayed in a browser:

Razor-Img9
Razor-Img9

Converting and testing data types

Although ASP.NET can usually determine a data type automatically, sometimes it can’t. Therefore, you might need to help ASP.NET out by performing an explicit conversion. Even if you don’t have to convert types, sometimes it’s helpful to test to see what type of data you might be working with.

The most common case is that you have to convert a string to another type, such as to an integer or date. The following example shows a typical case where you must convert a string to a number.

[!code-vbhtmlMain]

   1:  @Code
   2:      Dim total = 0
   3:      Dim totalMessage = ""
   4:      if IsPost Then
   5:          ' Retrieve the numbers that the user entered.
   6:          Dim num1 = Request("text1")
   7:          Dim num2 = Request("text2")
   8:          ' Convert the entered strings into integers numbers and add.
   9:          total = num1.AsInt() + num2.AsInt()
  10:          totalMessage = "Total = " & total
  11:      End If
  12:  End Code

As a rule, user input comes to you as strings. Even if you’ve prompted the user to enter a number, and even if they’ve entered a digit, when user input is submitted and you read it in code, the data is in string format. Therefore, you must convert the string to a number. In the example, if you try to perform arithmetic on the values without converting them, the following error results, because ASP.NET cannot add two strings:

Cannot implicitly convert type 'string' to 'int'.

To convert the values to integers, you call the AsInt method. If the conversion is successful, you can then add the numbers.

The following table lists some common conversion and test methods for variables.

Method Description Example
AsInt(), IsInt() Converts a string that represents a whole number (like “593”) to an integer. [!code-vbMain]
   1:  Dim myIntNumber = 0
   2:  Dim myStringNum = "539"
   3:  If myStringNum.IsInt() Then
   4:      myIntNumber = myStringNum.AsInt()
   5:  End If
AsBool(), IsBool() Converts a string like “true” or “false” to a Boolean type. [!code-vbMain]
   1:  Dim myStringBool = "True"
   2:  Dim myVar = myStringBool.AsBool()
AsFloat(), IsFloat() Converts a string that has a decimal value like “1.3” or “7.439” to a floating-point number. [!code-vbMain]
   1:  Dim myStringFloat = "41.432895"
   2:  Dim myFloatNum = myStringFloat.AsFloat()
AsDecimal(), IsDecimal() Converts a string that has a decimal value like “1.3” or “7.439” to a decimal number. (In ASP.NET, a decimal number is more precise than a floating-point number.) [!code-vbMain]
   1:  Dim myStringDec = "10317.425"
   2:  Dim myDecNum = myStringDec.AsDecimal()
AsDateTime(), IsDateTime() Converts a string that represents a date and time value to the ASP.NET DateTime type. [!code-vbMain]
   1:  Dim myDateString = "12/27/2012"
   2:  Dim newDate = myDateString.AsDateTime()
ToString() Converts any other data type to a string. [!code-vbMain]
   1:  Dim num1 As Integer = 17
   2:  Dim num2 As Integer = 76
   3:   
   4:  ' myString is set to 1776
   5:  Dim myString as String = num1.ToString() & _
   6:      num2.ToString()

Operators

An operator is a keyword or character that tells ASP.NET what kind of command to perform in an expression. Visual Basic supports many operators, but you only need to recognize a few to get started developing ASP.NET web pages. The following table summarizes the most common operators.

Operator Description Examples
+ - * / Math operators used in numerical expressions. [!code-vbMain]
   1:  @(5 + 13)
   2:   
   3:  Dim netWorth = 150000
   4:  Dim newTotal = netWorth * 2
   5:  @(newTotal / 2)
= Assignment and equality. Depending on context, either assigns the value on the right side of a statement to the object on the left side, or checks the values for equality. [!code-vbMain]
   1:  Dim age = 17
   2:   
   3:  Dim income = Request("AnnualIncome")
<> Inequality. Returns True if the values are not equal. [!code-vbMain]
   1:  Dim theNum = 13
   2:  If theNum <> 15 Then
   3:      ' Do something.
   4:  End If
< > <= >= Less than, greater than, less than or equal, and greater than or equal. [!code-vbMain]
   1:  If 2 < 3 Then
   2:      ' Do something.
   3:  End If
   4:   
   5:  Dim currentCount = 12
   6:  If currentCount >= 12 Then
   7:      ' Do something.
   8:  End If
& Concatenation, which is used to join strings. [!code-vbhtmlMain]
   1:  ' The displayed result is "abcdef".
   2:  @("abc" & "def")
+= -= The increment and decrement operators, which add and subtract 1 (respectively) from a variable. [!code-vbMain]
   1:  Dim theCount As Integer = 0
   2:  theCount += 1 ' Adds 1 to count
. Dot. Used to distinguish objects and their properties and methods. [!code-vbMain]
   1:  Dim myUrl = Request.Url
   2:  Dim count = Request("Count").AsInt()
() Parentheses. Used to group expressions, to pass parameters to methods, and to access members of arrays and collections. [!code-vbhtmlMain]
   1:  @(3 + 7)
   2:   
   3:  @Request.MapPath(Request.FilePath)
Not Not. Reverses a true value to false and vice versa. Typically used as a shorthand way to test for False (that is, for not True). [!code-vbMain]
   1:  Dim taskCompleted As Boolean = False
   2:  ' Processing.
   3:  If Not taskCompleted Then 
   4:      ' Continue processing
   5:  End If
AndAlso OrElse Logical AND and OR, which are used to link conditions together. [!code-vbMain]
   1:  Dim myTaskCompleted As Boolean = false
   2:  Dim totalCount As Integer = 0          
   3:  ' Processing.
   4:  If (Not myTaskCompleted) AndAlso _
   5:           totalCount < 12 Then 
   6:      ' Continue processing.
   7:  End If

Working with File and Folder Paths in Code

You’ll often work with file and folder paths in your code. Here is an example of physical folder structure for a website as it might appear on your development computer:

C:\WebSites\MyWebSite default.cshtml datafile.txt \images Logo.jpg \styles Styles.css

Here are some essential details about URLs and paths:

Here’s an example to help you understand the differences:

Complete URL http://mycompanyserver/humanresources/CompanyPolicy.htm
Server name mycompanyserver
Virtual path /humanresources/CompanyPolicy.htm
Physical path C:.htm

The virtual root is /, just like the root of your C: drive is . (Virtual folder paths always use forward slashes.) The virtual path of a folder doesn’t have to have the same name as the physical folder; it can be an alias. (On production servers, the virtual path rarely matches an exact physical path.)

When you work with files and folders in code, sometimes you need to reference the physical path and sometimes a virtual path, depending on what objects you’re working with. ASP.NET gives you these tools for working with file and folder paths in code: the Server.MapPath method, and the ~ operator and Href method.

Converting virtual to physical paths: the Server.MapPath method

The Server.MapPath method converts a virtual path (like /default.cshtml) to an absolute physical path (like C:.cshtml). You use this method any time you need a complete physical path. A typical example is when you’re reading or writing a text file or image file on the web server.

You typically don’t know the absolute physical path of your site on a hosting site’s server, so this method can convert the path you do know — the virtual path — to the corresponding path on the server for you. You pass the virtual path to a file or folder to the method, and it returns the physical path:

[!code-vbhtmlMain]

   1:  @Code
   2:      Dim dataFilePath = "~/dataFile.txt"
   3:  End Code    
   4:   
   5:  <!-- Displays a physical path C:\Websites\MyWebSite\datafile.txt  --> 
   6:  <p>@Server.MapPath(dataFilePath)</p>

Referencing the virtual root: the ~ operator and Href method

In a .cshtml or .vbhtml file, you can reference the virtual root path using the ~ operator. This is very handy because you can move pages around in a site, and any links they contain to other pages won’t be broken. It’s also handy in case you ever move your website to a different location. Here are some examples:

[!code-vbhtmlMain]

   1:  @Code
   2:      Dim myImagesFolder = "~/images"
   3:      Dim myStyleSheet = "~/styles/StyleSheet.css"       
   4:  End Code

If the website is http://myserver/myapp, here’s how ASP.NET will treat these paths when the page runs:

(You won’t actually see these paths as the values of the variable, but ASP.NET will treat the paths as if that’s what they were.)

You can use the ~ operator both in server code (as above) and in markup, like this:

[!code-htmlMain]

   1:  <!-- Examples of using the ~ operator in markup in ASP.NET Web Pages -->
   2:   
   3:  <a href="~/Default">Home</a>
   4:  <img src="~/images/MyImages.png" />

In markup, you use the ~ operator to create paths to resources like image files, other web pages, and CSS files. When the page runs, ASP.NET looks through the page (both code and markup) and resolves all the ~ references to the appropriate path.

Conditional Logic and Loops

ASP.NET server code lets you perform tasks based on conditions and write code that repeats statements a specific number of times that is, code that runs a loop).

Testing conditions

To test a simple condition you use the If...Then statement, which returns True or False based on a test you specify:

[!code-vbhtmlMain]

   1:  @Code
   2:      Dim showToday = True
   3:      If showToday Then
   4:          DateTime.Today
   5:      End If
   6:  End Code

The If keyword starts a block. The actual test (condition) follows the If keyword and returns true or false. The If statement ends with Then. The statements that will run if the test is true are enclosed by If and End If. An If statement can include an Else block that specifies statements to run if the condition is false:

[!code-vbhtmlMain]

   1:  @Code
   2:      Dim showToday = False
   3:      If showToday Then
   4:          DateTime.Today
   5:      Else
   6:          @<text>Sorry!</text>
   7:      End If
   8:  End Code

If an If statement starts a code block, you don’t have to use the normal Code...End Code statements to include the blocks. You can just add @ to the block, and it will work. This approach works with If as well as other Visual Basic programming keywords that are followed by code blocks, including For, For Each, Do While, etc.

[!code-vbhtmlMain]

   1:  @If showToday Then
   2:      DateTime.Today
   3:  Else
   4:      @<text>Sorry!</text>
   5:  End If

You can add multiple conditions using one or more ElseIf blocks:

[!code-vbhtmlMain]

   1:  @Code
   2:      Dim theBalance = 4.99
   3:      If theBalance = 0 Then
   4:          @<p>You have a zero balance.</p>
   5:      ElseIf theBalance > 0 AndAlso theBalance <= 5 Then
   6:          ' If the balance is above 0 but less than
   7:          ' or equal to $5, display this message.
   8:          @<p>Your balance of $@theBalance is very low.</p>
   9:      Else
  10:          ' For balances greater than $5, display balance.
  11:          @<p>Your balance is: $@theBalance</p>
  12:      End If    
  13:  End Code

In this example, if the first condition in the If block is not true, the ElseIf condition is checked. If that condition is met, the statements in the ElseIf block are executed. If none of the conditions are met, the statements in the Else block are executed. You can add any number of ElseIf blocks, and then close with an Else block as the “everything else” condition.

To test a large number of conditions, use a Select Case block:

[!code-vbhtmlMain]

   1:  @Code
   2:      Dim weekday = "Wednesday"
   3:      Dim greeting = ""
   4:      
   5:      Select Case weekday
   6:          Case "Monday"
   7:              greeting = "Ok, it's a marvelous Monday."
   8:          Case "Tuesday"
   9:              greeting = "It's a tremendous Tuesday."
  10:          Case "Wednesday"
  11:              greeting = "Wild Wednesday is here!"
  12:          Case Else
  13:              greeting = "It's some other day, oh well."
  14:      End Select
  15:  End Code
  16:  <p>Since it is @weekday, the message for today is: @greeting</p>

The value to test is in parentheses (in the example, the weekday variable). Each individual test uses a Case statement that lists a value. If the value of a Case statement matches the test value, the code in that Case block is executed.

The result of the last two conditional blocks displayed in a browser:

Razor-Img10
Razor-Img10

Looping code

You often need to run the same statements repeatedly. You do this by looping. For example, you often run the same statements for each item in a collection of data. If you know exactly how many times you want to loop, you can use a For loop. This kind of loop is especially useful for counting up or counting down:

[!code-vbhtmlMain]

   1:  @For i = 10 To 20
   2:      @<p>Item #: @i</p>
   3:  Next i

The loop begins with the For keyword, followed by three elements:

The line of code between the For and Next lines contains the code that runs for each iteration of the loop. The markup creates a new paragraph (<p> element) each time and adds a line to the output, displaying the value of i (the counter). When you run this page, the example creates 11 lines displaying the output, with the text in each line indicating the item number.

Razor-Img11
Razor-Img11

If you’re working with a collection or array, you often use a For Each loop. A collection is a group of similar objects, and the For Each loop lets you carry out a task on each item in the collection. This type of loop is convenient for collections, because unlike a For loop, you don’t have to increment the counter or set a limit. Instead, the For Each loop code simply proceeds through the collection until it’s finished.

This example returns the items in the Request.ServerVariables collection (which contains information about your web server). It uses a For Each loop to display the name of each item by creating a new <li> element in an HTML bulleted list.

[!code-vbhtmlMain]

   1:  <ul>
   2:  @For Each myItem In Request.ServerVariables
   3:      @<li>@myItem</li>
   4:  Next myItem
   5:  </ul>

The For Each keyword is followed by a variable that represents a single item in the collection (in the example, myItem), followed by the In keyword, followed by the collection you want to loop through. In the body of the For Each loop, you can access the current item using the variable that you declared earlier.

Razor-Img12
Razor-Img12

To create a more general-purpose loop, use the Do While statement:

[!code-vbhtmlMain]

   1:  @Code
   2:      Dim countNum = 0
   3:      Do While countNum < 50
   4:          countNum += 1
   5:          @<p>Line #@countNum: </p>
   6:      Loop
   7:  End Code

This loop begins with the Do While keyword, followed by a condition, followed by the block to repeat. Loops typically increment (add to) or decrement (subtract from) a variable or object used for counting. In the example, the += operator adds 1 to the value of a variable each time the loop runs. (To decrement a variable in a loop that counts down, you would use the decrement operator -=.)

Objects and Collections

Nearly everything in an ASP.NET website is an object, including the web page itself. This section discusses some important objects you’ll work with frequently in your code.

Page objects

The most basic object in ASP.NET is the page. You can access properties of the page object directly without any qualifying object. The following code gets the page’s file path, using the Request object of the page:

[!code-vbhtmlMain]

   1:  @Code
   2:      Dim path = Request.FilePath
   3:  End Code

You can use properties of the Page object to get a lot of information, such as:

Collection objects (arrays and dictionaries)

A collection is a group of objects of the same type, such as a collection of Customer objects from a database. ASP.NET contains many built-in collections, like the Request.Files collection.

You’ll often work with data in collections. Two common collection types are the array and the dictionary. An array is useful when you want to store a collection of similar items but don’t want to create a separate variable to hold each item:

[!code-vbhtmlMain]

   1:  <h3>Team Members</h3>
   2:  @Code
   3:      Dim teamMembers() As String = {"Matt", "Joanne", "Robert", "Nancy"}
   4:      For Each name In teamMembers
   5:          @<p>@name</p>
   6:      Next name
   7:  End Code

With arrays, you declare a specific data type, such as String, Integer, or DateTime. To indicate that the variable can contain an array, you add parentheses to the variable name in the declaration (such as Dim myVar() As String). You can access items in an array using their position (index) or by using the For Each statement. Array indexes are zero-based — that is, the first item is at position 0, the second item is at position 1, and so on.

[!code-vbhtmlMain]

   1:  @Code
   2:      Dim teamMembers() As String = {"Matt", "Joanne", "Robert", "Nancy"}
   3:      @<p>The number of names in the teamMembers array: @teamMembers.Length </p>
   4:      @<p>Robert is now in position: @Array.IndexOf(teamMembers, "Robert")</p>
   5:      @<p>The array item at position 2 (zero-based) is @teamMembers(2)</p>
   6:      @<h3>Current order of team members in the list</h3>
   7:      For Each name In teamMembers
   8:          @<p>@name</p>
   9:      Next name
  10:      @<h3>Reversed order of team members in the list</h3>
  11:      Array.Reverse(teamMembers)
  12:      For Each reversedItem In teamMembers
  13:          @<p>@reversedItem</p>
  14:      Next reversedItem
  15:  End Code

You can determine the number of items in an array by getting its Length property. To get the position of a specific item in the array (that is, to search the array), use the Array.IndexOf method. You can also do things like reverse the contents of an array (the Array.Reverse method) or sort the contents (the Array.Sort method).

The output of the string array code displayed in a browser:

Razor-Img13
Razor-Img13

A dictionary is a collection of key/value pairs, where you provide the key (or name) to set or retrieve the corresponding value:

[!code-vbhtmlMain]

   1:  @Code
   2:      Dim myScores = New Dictionary(Of String, Integer)()
   3:      myScores.Add("test1", 71)
   4:      myScores.Add("test2", 82)
   5:      myScores.Add("test3", 100)
   6:      myScores.Add("test4", 59)
   7:  End Code
   8:  <p>My score on test 3 is: @myScores("test3")%</p>
   9:  @Code 
  10:      myScores("test4") = 79
  11:  End Code
  12:  <p>My corrected score on test 4 is: @myScores("test4")%</p>

To create a dictionary, you use the New keyword to indicate that you’re creating a new Dictionary object. You can assign a dictionary to a variable using the Dim keyword. You indicate the data types of the items in the dictionary using parentheses ( ( ) ). At the end of the declaration, you must add another pair of parentheses, because this is actually a method that creates a new dictionary.

To add items to the dictionary, you can call the Add method of the dictionary variable (myScores in this case), and then specify a key and a value. Alternatively, you can use parentheses to indicate the key and do a simple assignment, as in the following example:

[!code-vbhtmlMain]

   1:  @Code
   2:      myScores("test4") = 79
   3:  End Code

To get a value from the dictionary, you specify the key in parentheses:

[!code-vbhtmlMain]

   1:  @myScores("test4")

Calling Methods with Parameters

As you saw earlier in this article, the objects that you program with have methods. For example, a Database object might have a Database.Connect method. Many methods also have one or more parameters. A parameter is a value that you pass to a method to enable the method to complete its task. For example, look at a declaration for the Request.MapPath method, which takes three parameters:

[!code-vbMain]

   1:  Public Overridable Function MapPath (virtualPath As String, _
   2:      baseVirtualDir As String, _
   3:      allowCrossAppMapping As Boolean)

This method returns the physical path on the server that corresponds to a specified virtual path. The three parameters for the method are virtualPath, baseVirtualDir, and allowCrossAppMapping. (Notice that in the declaration, the parameters are listed with the data types of the data that they’ll accept.) When you call this method, you must supply values for all three parameters.

When you’re using Visual Basic with the Razor syntax, you have two options for passing parameters to a method: positional parameters or named parameters. To call a method using positional parameters, you pass the parameters in a strict order that’s specified in the method declaration. (You would typically know this order by reading documentation for the method.) You must follow the order, and you can’t skip any of the parameters — if necessary, you pass an empty string ("") or null for a positional parameter that you don’t have a value for.

The following example assumes you have a folder named scripts on your website. The code calls the Request.MapPath method and passes values for the three parameters in the correct order. It then displays the resulting mapped path.

[!code-vbhtmlMain]

   1:  @Code
   2:      ' Pass parameters to a method using positional parameters.
   3:      Dim myPathPositional = Request.MapPath("/scripts", "/", true)
   4:  End Code
   5:  <p>@myPathPositional</p>

When there are many parameters for a method, you can keep your code cleaner and more readable by using named parameters. To call a method using named parameters, specify the parameter name followed by := and then provide the value. An advantage of named parameters is that you can add them in any order you want. (A disadvantage is that the method call is not as compact.)

The following example calls the same method as above, but uses named parameters to supply the values:

[!code-vbhtmlMain]

   1:  @Code
   2:      ' Pass parameters to a method using named parameters.
   3:      Dim myPathNamed = Request.MapPath(baseVirtualDir:= "/", allowCrossAppMapping:= true, virtualPath:= "/scripts")
   4:  End Code
   5:  <p>@myPathNamed</p>

As you can see, the parameters are passed in a different order. However, if you run the previous example and this example, they’ll return the same value.

Handling Errors

Try-Catch statements

You’ll often have statements in your code that might fail for reasons outside your control. For example:

In programming terms, these situations are called exceptions. If your code encounters an exception, it generates (throws) an error message that is, at best, annoying to users.

Razor-Img14
Razor-Img14

In situations where your code might encounter exceptions, and in order to avoid error messages of this type, you can use Try/Catch statements. In the Try statement, you run the code that you’re checking. In one or more Catch statements, you can look for specific errors (specific types of exceptions) that might have occurred. You can include as many Catch statements as you need to look for errors that you’re anticipating.

[!NOTE] We recommend that you avoid using the Response.Redirect method in Try/Catch statements, because it can cause an exception in your page.

The following example shows a page that creates a text file on the first request and then displays a button that lets the user open the file. The example deliberately uses a bad file name so that it will cause an exception. The code includes Catch statements for two possible exceptions: FileNotFoundException, which occurs if the file name is bad, and DirectoryNotFoundException, which occurs if ASP.NET can’t even find the folder. (You can uncomment a statement in the example in order to see how it runs when everything works properly.)

If your code didn’t handle the exception, you would see an error page like the previous screen shot. However, the Try/Catch section helps prevent the user from seeing these types of errors.

[!code-vbhtmlMain]

   1:  @Code
   2:      Dim dataFilePath = "~/dataFile.txt"
   3:      Dim fileContents = ""
   4:      Dim physicalPath = Server.MapPath(dataFilePath)
   5:      Dim userMessage = "Hello world, the time is " + DateTime.Now
   6:      Dim userErrMsg = ""
   7:      Dim errMsg = ""
   8:      
   9:      If IsPost Then
  10:          ' When the user clicks the "Open File" button and posts
  11:          ' the page, try to open the file.
  12:          Try
  13:              ' This code fails because of faulty path to the file.
  14:              fileContents = File.ReadAllText("c:\batafile.txt")
  15:              
  16:              ' This code works. To eliminate error on page, 
  17:              ' comment the above line of code and uncomment this one.
  18:              ' fileContents = File.ReadAllText(physicalPath)
  19:              
  20:          Catch ex As FileNotFoundException
  21:              ' You can use the exception object for debugging, logging, etc.
  22:              errMsg = ex.Message
  23:              ' Create a friendly error message for users.
  24:              userErrMsg = "The file could not be opened, please contact " _
  25:                  & "your system administrator."
  26:                  
  27:          Catch ex As DirectoryNotFoundException
  28:              ' Similar to previous exception.
  29:              errMsg = ex.Message
  30:              userErrMsg = "The file could not be opened, please contact " _
  31:                  & "your system administrator."
  32:          End Try
  33:      Else
  34:          ' The first time the page is requested, create the text file.
  35:          File.WriteAllText(physicalPath, userMessage)
  36:      End If
  37:  End Code
  38:  <!DOCTYPE html>
  39:  <html lang="en">
  40:      <head>
  41:          <meta charset="utf-8" />
  42:          <title>Try-Catch Statements</title>
  43:      </head>
  44:      <body>  
  45:      <form method="POST" action="" >
  46:        <input type="Submit" name="Submit" value="Open File"/>
  47:      </form>
  48:      
  49:      <p>@fileContents</p>
  50:      <p>@userErrMsg</p>
  51:      
  52:      </body>
  53:  </html>

Additional Resources

Reference Documentation





Comments ( )
<00>  <01>  <02>  <03>  <04>  <05>  <06>  <07>  <08>  <09>  <10>  <11>  <12>  <13>  <14>  <15>  <16>  <17>  <18>  <19>  <20>  <21>  <22>  <23
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-pages/overview/getting-started/introducing-razor-syntax-vb.htm
<SITEMAP>  <MVC>  <ASP>  <NET>  <DATA>  <KIOSK>  <FLEX>  <SQL>  <NOTES>  <LINUX>  <MONO>  <FREEWARE>  <DOCS>  <ENG>  <CHAT ME>  <ABOUT ME>  < THANKS ME>