Razor Syntax Basics
Learn how Razor combines HTML and C# in ASP.NET Core views so you can build dynamic pages with expressions, code blocks, conditions, loops, and strongly typed models.
Part 1: What Razor Is
Razor is the view engine used in ASP.NET Core MVC. It allows you to mix standard HTML with C# code inside the same
.cshtml file. This makes your pages dynamic, so the content shown to the user can change according to data,
logic, and application state.
Razor is especially useful when you want to display values from a controller, show model data, loop through lists, or render different content based on conditions.
Part 2: The @ Symbol and Code Blocks
The @ symbol tells Razor to switch from HTML into C# mode.
You can use it for inline expressions or for larger code blocks.
string name = "Alice";
int score = 95;
}
<p>Student: @name</p>
<p>Score: @score</p>
In this example, the values of name and score are inserted directly into the HTML output.
Part 3: Conditions and Loops
Razor supports C# control structures such as if, else, and foreach.
This allows you to show different content depending on logic.
var fruits = new List<string> { "Apple", "Banana", "Orange" };
}
@if (fruits.Count > 0)
{
<ul>
@foreach (var fruit in fruits)
{
<li>@fruit</li>
}
</ul>
}
This pattern is very common when displaying records from a database or model collection.
Part 4: Using Models in Razor Views
Razor becomes even more powerful when used with strongly typed models. At the top of a view, you can declare the model type
with @model, then access its properties using @Model.
<h2>@Model.Name</h2>
<p>Course: @Model.Course</p>
<p>Age: @Model.Age</p>
This makes views more structured and easier to maintain than relying only on ViewBag or ViewData.
Part 5: Best Practices
- Use Razor for presentation, not heavy business logic
- Keep code blocks short and readable
- Prefer strongly typed models for structured data
- Use layouts and partial views for reusable UI
Once you understand Razor syntax, building dynamic ASP.NET Core pages becomes much easier and more professional.