ASP.NET Razor Syntax Example: CSHTML

This C# example uses the razor syntax in an ASP.NET page. It shows a cshtml file.

Razor syntax. New versions of ASP.NET support the Razor syntax.

This is a shorter, sharper syntax form that involves less typing. It is clear. On a CSHTML page, we use C# code inline with HTML.

 

 

Example. This syntax uses the @ character to begin a code region. In the code region, we can use HTML tags directly, without placing them in literals. This makes the cshtml easier to read.

 

Quotes: A big advantage of razor syntax is how quotation marks need no escaping. So the HTML is much easier to type.

A variable in the C# code can be referenced directly in an HTML part with the @ character as well. Please note how the "i" variable is referenced within the first HTML line. We then test the "i" in C# code in the typical way.

ForIf

Based on:

.NET 4.5

Page that uses Razor syntax: ASP.NET

@{
    // Loop over numbers and display them.
    for (int i = 0; i < 5; i++)
    {
	<b>Number: @i</b><br />
	if (i == 3)
	{
	    <b style="color:red">Three</b><br />
	}
    }
}

Output

	<b>Number: 0</b><br />
	<b>Number: 1</b><br />
	<b>Number: 2</b><br />
	<b>Number: 3</b><br />
	    <b style="color:red">Three</b><br />
	<b>Number: 4</b><br />

 

Begin. To begin using cshtml and the razor syntax, please use Visual Studio 2013. And create a new website from the File menu. Select the ASP.NET Website project with Razor (V3) syntax. This uses the C# language.

 

Default: The site may have some prefilled content. You can replace the text in default.cshtml with the code sample on this page.

Research. The ASP.NET contains tutorials on Razor syntax. The material there is more detailed than the material on this site. I recommend checking all possible references when learning.

Introducing Razor Syntax: ASP.NET

Also: A great way to learn about this syntax is to create a website (or test website) in it. This approach is often better than tutorials.

 

Comments are important. With them, we provide clues about why a program is written in a certain way. This helps us when we try to fix a bug in a program written years ago. Razor syntax uses @* for comments.

 

Note: Because C# code is embedded in this syntax, we can use // and other C# comments in Razor pages as well.

Page with comment: ASP.NET

@* Do something useful.
   Or wait until tomorrow. *@

 

Summary. Razor addresses a big complaint about ASP.NET—its confusing syntax. At the same time, it fixes a problem with generating HTML in C# code—the need to escape quote characters. In this sense it gives us the best parts of both languages.