Razor
Razor syntax was introduced with MVC 3 (Visual Studio 2010). In Razor view you can write a mix of HTML tags and server side code. You can use C# to write server side code inside Razor view. Razor uses @ character for server side code instead of traditional <% %>. The syntax is simpler – it is enough to start the code with @ sign and you do not need to close %> tags as it was in aspx.
Single line expression
Start with @ symbol to write C# code with HTML code. A single line expression does not require a semicolon at the end. For example:
<h2>@DateTime.Now.ToShortDateString()</h2>
Multiple lines
Multiple lines of server side code need to be enclosed in braces @{ … }. Each line ends with a semicolon.
@{
var date = DateTime.Now.ToShortDateString();
var message = "Hello";
}
<h2>Current date is: @date</h2>
<h3>@messag</h3>
Text must be enclosed in HTML tags. To display text within code block, if you do not want to use any formatting, use @: or .
@{
var currentDate = DateTime.Now.ToShortDateString();
string myMessage = "Hello!";
@:Current date is: @currentDate
<text>I say: </text> @myMessage
}
Text with @ sign
You can use @@ sign to display the @ sign.
With @ sign you can use several constructions, like:
If-else block
The if-else code block must be enclosed in braces { }- even for single statement.
@if (DateTime.Today.DayOfWeek == DayOfWeek.Saturday)
{
@:Party time!;
}
else
{
@:Get to work;
}
Foreach loop
@{
List<string> daysOfWeek = new List<string>() { "Monday", "Tuesday" };
foreach (string day in daysOfWeek)
{
@day;
}
}
For loop
@for (int i = 0; i < 5; i++)
{
@i.ToString()
}
Declaring variables
Variable declared in a code block enclosed in brackets can be used inside html with @ symbol.
@{
string dayOfWeek = DateTime.Today.DayOfWeek.ToString();
}
@dayOfWeek
File extensions
Razor views files with C# code have .cshtml extension. View file extensions can be as follows:
-
- .cshtml- C# Razor view. Supports C# with html tags
- .vbhtml – Visual Basic Razor view. Supports Visual Basic with html tags
- .aspx – ASP.Net web form
- .ascx – ASP.NET web control – reusable functionality that will be applied on many pages in the project