Chapter 18: ASP.NET Razor
1. What exactly is Razor?
Razor is a server-side markup syntax created by Microsoft (introduced in 2010 with ASP.NET Web Pages and ASP.NET MVC 3).
Its only job is to let you mix C# (or VB.NET) code cleanly inside HTML — so the server can generate dynamic HTML before sending it to the browser.
Key characteristics:
- File extensions: .cshtml (C# + HTML) or .vbhtml (VB.NET + HTML)
- Starts with the @ symbol — that’s the magic trigger
- Very little ceremony — no need for <%%> tags like in classic ASP or PHP’s <?php ?>
- Designed to feel natural if you already know HTML + a little C#
- Razor code runs on the server — browser never sees @ or C# code
Think of Razor as the “bridge” between static HTML and dynamic C# logic.
2. Why was Razor invented? (The history in 2 minutes)
Before Razor (1998–2010):
- Classic ASP → <% Response.Write(“Hello”) %> — ugly & verbose
- ASP.NET Web Forms → server controls (<asp:Label>) — felt heavy, magic, hard to control HTML
- PHP / JSP → <?php echo $name; ?> — works, but mixing logic & markup gets messy
Microsoft wanted:
- Clean HTML output
- Full power of C# / VB.NET
- No drag-and-drop designer lock-in
- Easy for front-end developers to learn
→ Razor was born: minimal syntax, beautiful HTML, full language power.
3. The 5 Core Rules of Razor Syntax (Write these down!)
- @ starts C# code@DateTime.Now → prints current time @Model.Name → prints a property
- @{ … } is a code block (multiple lines of C#) Everything inside is pure C# — no HTML output unless you explicitly write it
- Single-line expressions → just @expression@(price * quantity) for calculations @user.IsAdmin ? “Yes” : “No”
- Transition back to HTML is automatic After @if { … } Razor knows when you’re back in HTML
- To force HTML output inside code block use @: or <text> (rare, but important)
4. Real Examples – Let’s Build Understanding Step by Step
Example 1 – Hello World + Variables
Index.cshtml
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
@{ // Code block — pure C# var city = "Hyderabad"; var temperature = 32; var message = $"Welcome to {city}! It's {temperature}°C today."; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Razor Basics</title> </head> <body> <h1>Hello from Razor!</h1> <p>@message</p> <p>Server time right now: @DateTime.Now.ToString("dddd, dd MMMM yyyy - hh:mm tt")</p> <p>Quick math: 15 × 4 = @(15 * 4)</p> </body> </html> |
→ Browser sees only clean HTML — no @ symbols.
Example 2 – Conditionals & Loops (Most Common Use)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
@{ var hour = DateTime.Now.Hour; var name = "Webliance"; var products = new List<string> { "Idli", "Dosa", "Vada", "Pongal" }; } <h2>Good @(hour < 12 ? "Morning" : hour < 17 ? "Afternoon" : "Evening"), @name!</h2> <h3>Today's Specials in Hyderabad:</h3> <ul> @foreach (var item in products) { <li>@item.ToUpper()</li> } </ul> @if (products.Count > 3) { <p style="color: green;">Wow — lots of choices today!</p> } else { <p style="color: orange;">Only a few items left...</p> } |
→ Notice how Razor automatically switches between C# and HTML — very fluid.
Example 3 – Layouts & PageData (Sharing Data)
_Layout.cshtml (in Shared folder)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<!DOCTYPE html> <html> <head> <title>@Page.Title - My Site</title> <link href="~/css/site.css" rel="stylesheet" /> </head> <body> <header> <h1>@Page.SiteName</h1> <nav> <a class="@(Page.ActivePage == "home" ? "active" : "")" href="/">Home</a> <a class="@(Page.ActivePage == "about" ? "active" : "")" href="/About">About</a> </nav> </header> <main> @RenderBody() </main> <footer>© @DateTime.Now.Year</footer> @RenderSection("scripts", required: false) </body> </html> |
Home.cshtml
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@{ Layout = "~/Shared/_Layout.cshtml"; Page.Title = "Home"; Page.SiteName = "Webliance Learning"; Page.ActivePage = "home"; } <h2>Welcome to Razor Pages!</h2> <p>This content appears inside @RenderBody() of the layout.</p> @section scripts { <script>console.log("Home page loaded!");</script> } |
→ This is the real power of Razor — clean separation + data sharing.
Example 4 – Forms & Model Binding (Modern Razor Style)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
@page @model IndexModel <h1>Contact Form</h1> <form method="post"> <label>Name:</label> <input asp-for="Name" /> <label>Email:</label> <input asp-for="Email" /> <button type="submit">Send</button> </form> @if (Model.Message != null) { <div class="alert alert-success"> @Model.Message </div> } |
Index.cshtml.cs (code-behind / PageModel)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class IndexModel : PageModel { [BindProperty] public string Name { get; set; } [BindProperty] public string Email { get; set; } public string Message { get; set; } public void OnPost() { Message = $"Thank you, {Name}! We'll email {Email} soon."; } } |
→ This is ASP.NET Core Razor Pages style — same Razor syntax, but with stronger model binding.
5. Razor vs Older Ways – Quick Comparison
| Feature | Classic ASP (1998) | PHP | Razor (2010+) |
|---|---|---|---|
| Syntax | <% =variable %> | <?php echo $var; ?> | @variable |
| Code blocks | <% … %> | <?php … ?> | @{ … } |
| HTML readability | Poor | Medium | Excellent |
| Language power | VBScript | PHP | Full C# / VB.NET |
| Modern status (2026) | Legacy | Still used | Current standard in .NET |
6. Final Teacher Summary
ASP.NET Razor is:
- A server-side templating syntax (.cshtml files)
- Uses @ to switch to C# code inside HTML
- Designed for clean, readable markup + powerful logic
- Powers:
- Classic ASP.NET Web Pages (what we studied earlier)
- ASP.NET MVC Views
- ASP.NET Core Razor Pages (recommended today)
- Razor Components in Blazor
Once you master @, @{ }, @if, @foreach, @model, and layouts — you can build almost any dynamic web page in .NET.
Homework question for you:
- Do you want to see Razor in ASP.NET Core (modern way) next?
- Or compare Razor vs Blazor syntax?
- Or build a small Razor Pages mini-app together?
Just tell me — we’re going to make you a Razor pro from Hyderabad! 🚀🇮🇳
