Lesson 11 of 40 Views Beginner 35 min

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.

@model Student

<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

Once you understand Razor syntax, building dynamic ASP.NET Core pages becomes much easier and more professional.

VISUAL STUDIO 2026 MADE EASY
Recommended Book

VISUAL STUDIO 2026 MADE EASY

Build real applications with C#, VB.NET, Python, JavaScript, C++, and .NET 10. A practical companion for mastering Visual Studio 2026 step by step.