
Razor Intro in ASP
Absolutely! Here’s a quick introduction to Razor syntax in ASP.NET to get you started:
Razor Syntax Intro in ASP.NET
Razor is a markup syntax that lets you embed C# code directly within HTML in ASP.NET MVC or ASP.NET Core views (.cshtml
files).
Key Features of Razor
Seamless integration of HTML and C#
Minimal syntax clutter — uses
@
to transition from HTML to C#Supports full C# language features
Auto-escapes output to prevent XSS by default
Supports layouts, partial views, and sections for reusable UI
Basic Razor Syntax
1. Output C# variables or expressions
@{ var name = "Alice";}<p>Hello, @name!</p>
The @name
outputs the value of the variable.
2. Code blocks
Use @{ ... }
to write multiple C# statements:
@{ var hour = DateTime.Now.Hour; var greeting = hour < 12 ? "Good morning" : "Good afternoon";}<h1>@greeting, welcome!</h1>
3. Control statements
You can write if
, for
, foreach
easily:
@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
@* This is a Razor comment and won't render *@
5. Using Models
You typically pass a model to the view to strongly type your data:
@model MyApp.Models.User<h2>Welcome, @Model.FirstName</h2>
Why use Razor?
Clean and readable syntax
Combines server-side logic and client-side markup efficiently
Used in ASP.NET MVC and ASP.NET Core for dynamic web pages
If you want me to show you Razor examples with forms, partial views, layouts, or integration with controllers, just ask!