
Webpages Razor in ASP
Sure! Here's a complete introduction to Razor in ASP.NET Web Pages — the syntax, features, and how it integrates with HTML to create dynamic web content.
? Razor in ASP.NET Web Pages
? What Is Razor?
Razor is a markup syntax used in ASP.NET Web Pages to embed server-based code (C# or VB) into HTML.
It starts with the @ symbol to switch from HTML to server-side code.
It's clean, lightweight, and does not require code-behind files.
?? Razor Syntax Basics
@{ var message = "Hello, Razor!";}<p>@message</p>
@{ ... }
is used to write C# code blocks.@variableName
is used to print a variable inside HTML.No semicolon (
;
) needed for inline code, but required inside code blocks.
? Example: Razor Page Structure
@{ Layout = "_Layout.cshtml"; // Optional layout page var title = "Home Page";}<!DOCTYPE html><html><head> <title>@title</title></head><body> <h1>Welcome to ASP.NET Web Pages</h1> <p>The time is: @DateTime.Now</p></body></html>
? Razor Key Concepts
Feature | Example | Description |
---|---|---|
Code block | @{ int x = 10; } | Define server-side code |
Expression | @x + 5 | Output the result directly in HTML |
Conditional | @if (x > 5) { ... } | Add logic in your page |
Loops | @for (int i = 0; i < 5; i++) | Create dynamic lists, tables, etc. |
Comments | @* This is a comment *@ | Razor-style comment (not shown in output) |
HTML inside code | @: <p>Hello</p> | Output raw HTML from within code block |
? Mixing HTML & Code
Razor is designed to blend seamlessly with HTML:
<ul>@for (int i = 0; i < 5; i++) { <li>Item @i</li>}</ul>
? Advantages of Razor
Cleaner and more readable than classic ASP or Web Forms.
No separate code-behind files.
Easy to learn and use for beginners.
Perfect for small to medium ASP.NET sites (especially with WebMatrix or Visual Studio Code).
? Razor in C# vs VB
C# uses
@{ }
,@if () { }
, etc.VB uses
@Code ... End Code
,If ... Then ... End If
.
Let me know if you want a comparison between C# and VB Razor, or if you want real-world examples like forms, login pages, or database output!