ASP.NET Razor is a new syntax for writing ASP.NET web pages. In this tutorial you will learn how to add ASP.NET Razor code to web pages. Razor is a server side markup language. Razor code starts with @. Further, the code blocks of Razor are enclosed in braces and the code statements end with semicolon. Declaration of variables in Razor is done with the var keyword. An example covering the general syntax of single statement blocks, multi-statement blocks, and inline expressions of Razor is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!-- Single statement blocks --> @{ var total = 7; } @{ var myMessage = "Hello World"; } <!-- Inline expressions --> <p>The value of your account is: @total</p> <p>The value of myMessage is: @myMessage</p> <!-- Multi-statement block --> @ { var greeting = "Welcome to our site!"; var weekDay = DateTime.Now.DayOfWeek; var greetingMessage = greeting + " Today is: " + weekDay; } <p>The greeting is: @greetingMessage</p> |
In the above example, code beings with @ and variables are declared with var keyword, as required. Besides, strings are enclosed within the quotation marks.
Now let’s see the changes that are made within a simple HTML code to convert it into a Razor equipped code. Consider the following HTML code:
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Hello World Page</title> </head> <body> <h1>Hello World Page</h1> <p>Hello World Page</p> </body> </html> |
After adding the Razor part, the above code would become:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Hello World Page</title> </head> <body> <h1>Hello World Page</h1> <p>Hello World Page</p> <p>The time is @DateTime.Now</p> </body> </html> |
The page contains ordinary HTML markup, with one addition: the @ marked Razor code. The Razor code does all the work of determining the current time on the server and display it. So basically leaning the Razor syntax is quite simple but it is quite a powerful markup language that can considerably enhance the web development techniques.