
Razor Syntax in ASP
Absolutely! Here's a clear overview of Razor Syntax in ASP.NET to help you write clean, dynamic web pages:
Razor Syntax in ASP.NET
Razor syntax lets you embed C# code seamlessly within HTML markup in .cshtml
views.
Basics of Razor Syntax
1. Code Blocks
Use @{ ... }
for multiple lines of C# code:
@{ var greeting = "Hello, World!"; var hour = DateTime.Now.Hour;}<p>@greeting</p><p>The hour is @hour</p>
2. Inline Expressions
Embed simple expressions or variables with @
:
<p>The current year is @DateTime.Now.Year</p><p>User: @User.Identity.Name</p>
3. Control Structures
Write if
, else
, loops, and switch statements with natural C# syntax:
@if (DateTime.Now.Hour < 12){ <p>Good morning!</p>}else{ <p>Good afternoon!</p>}<ul>@for (int i = 1; i <= 5; i++){ <li>Item @i</li>}</ul>
4. Comments
Razor comments (not rendered in output):
@* This is a Razor comment *@
HTML comments (rendered to client):
<!-- This is an HTML comment -->
5. Using Models
Declare the model type at the top:
@model MyApp.Models.Product<h2>Product: @Model.Name</h2><p>Price: @Model.Price.ToString("C")</p>
6. Escaping @
To output a literal @
, use @@
:
<p>Email: user@@example.com</p>
Summary Table
Usage | Syntax Example |
---|---|
Code block | @{ var x = 10; } |
Inline expression | @DateTime.Now |
If statement | @if (x > 5) { <p>Hi</p> } |
For loop | @for (int i=0; i<3; i++) { ... } |
Foreach loop | @foreach(var item in list) { ... } |
Model declaration | @model Namespace.ModelClass |
Razor comment | @* This is a comment *@ |
If you want examples on forms, layouts, partial views, or advanced Razor features, just ask!