ASP.NET Razor Syntax Example: CSHTMLUse the razor syntax in an ASP.NET page. See the syntax for a cshtml file.
dot net perls
Razor syntax. New versions of ASP.NET support the Razor syntax. This is a shorter syntax form that involves less typing. It is usually thought to be more readable. 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.
Variable A variable in the C# code can be referenced directly in an HTML part with the "@" character as well.
Note The "i" variable is referenced within the first HTML line. We then test the "i" in C# code in the typical way.
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.
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 /> } } }
<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 />
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.
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.
Page with comment: ASP.NET
@* Do something useful. Or wait until tomorrow. *@
Comments. Comments 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 special syntax for comments.
Note Because C# code is embedded in this syntax, we can use // and other C# comments in Razor pages as well.
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.
© 2007-2021 sam allen. see site info on the changelog