Razor is the default view engine in ASP.NET Core MVC. It provides a concise and elegant way to create dynamic web pages by combining C# code with HTML markup.
Key Razor Syntax Elements Code Blocks (@{…}): Purpose: Enclose multi-line C# code statements. Use Cases: Declaring variables Defining complex logic Executing database queries or other operations Expressions (@variable or @method()): Purpose: Embed C# expressions directly into the HTML output. Use Cases: Displaying values from variables or model properties Calling helper methods or functions Literals (@: or <text>): Purpose: Output raw text without HTML encoding. Use Cases: Displaying plain text, HTML snippets, or values that might contain HTML characters
Control Flow in Razor Views @if, @else, @elseif: Purpose: Conditional rendering of HTML blocks based on C# conditions. Example: @if (person.DateOfBirth.HasValue) { <p>Age: @(Math.Round((DateTime.Now – person.DateOfBirth).Value.TotalDays / 365.25)) years old</p> } else { <p>Date of birth is unknown</p> }
@switch: Purpose: Choose one of several blocks of code to execute based on the value of an expression. Example: @switch (person.PersonGender) { case Gender.Male: <p>November 19 is International Men’s Day</p> break; case Gender.Female: <p>March 8 is International Women’s Day</p> break; // … other cases … }
@foreach: Purpose: Iterate over a collection (e.g., a list or array) and render HTML for each item. Example: @foreach (var person in people) { <div>@person.Name, @person.PersonGender</div> }
@for: Purpose: Execute a code block a specific number of times. Example: @for (int i = 0; i < 5; i++) { <p>Iteration: @i</p> }