Razor is a server side markup language. Razor code starts with @.
Important Razor Syntax Rules
- Razor code starts with @
- Code blocks are enclosed in braces
- Code statements end with semicolon
- Variables are declared with the var keyword
- Strings are enclosed with quotation marks
Razor Code Starts with @
The @ character starts single statement blocks, multi-statement blocks, and inline expressions:| <!-- 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> |
Code Blocks are Enclosed in Braces
A code block includes one or more statements enclosed in braces.| <!-- Single statement block. --> @{ var theMonth = DateTime.Now.Month; } <p>The numeric value of the current month: @theMonth</p> <!-- Multi-statement block. --> @ { var outsideTemp = 79; var weatherMessage = "Hello, it is " + outsideTemp + " degrees."; } <p>Today's weather: @weatherMessage</p> |
Code Statements End With Semicolon
Inside a code block, each code statement must end with a semicolon. Inline expressions don't end with a semicolon.| <!-- Single-statement block --> @{ var theMonth = DateTime.Now.Month; } <!-- Multi-statement block --> @ { var outsideTemp = 79; var weatherMessage = "Hello, it is " + outsideTemp + " degrees."; } <!-- Inline expression, so no semicolon --> <p>Today's weather: @weatherMessage</p> |
The var Keyword Declares Variables
You can store values in variables, including strings, numbers, and dates, etc. You create a variable using the var keyword.| <!-- Storing a string --> @{ var welcomeMessage = "Welcome, new members!"; } <p>@welcomeMessage</p> <!-- Storing a date --> @{ var year = DateTime.Now.Year; } <!-- Displaying a variable --> <p>Welcome to our new members who joined in @year!</p> |
Strings are Enclosed with 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:<!-- Storing a string -->
@{ var welcomeMessage = "Welcome, new members!"; }
No comments:
Post a Comment