6. Views and Razor

A view is a .cshtml file that mixes HTML with C# using the Razor syntax. The @ symbol switches from HTML to C#. The @model line at the top declares the type of data the view receives, and Model gives access to it. Razor encodes output automatically, which protects against cross-site scripting.

Key points

  • @model declares the model type; @Model reads it.
  • @if, @foreach and @for write C# control flow directly in the page.
  • @(expression) is used when the expression has spaces or operators.
  • Use @@ to show a literal @ symbol.

Example: A strongly typed view

Views/Students/Index.cshtml
@model List<Student>

<h2>Students</h2>

@if (Model.Count == 0)
{
    <p>No students found.</p>
}
else
{
    <table>
        @foreach (var s in Model)
        {
            <tr>
                <td>@s.Name</td>
                <td>@s.Age</td>
            </tr>
        }
    </table>
}
Show explanation

The view loops through the list and writes one table row for each student, or shows a message when the list is empty.