Razor Views & Pages

Razor is ASP.NET's templating syntax for mixing C# directly into HTML — the @ character switches from HTML mode into C# mode wherever you need dynamic content.

A basic Razor view

A .cshtml file is mostly plain HTML, with @ marking the C# parts:

Razor Views/Home/Welcome.cshtml
@{
    var name = "Priya";
    var itemCount = 3;
}
<h1>Welcome, @name!</h1>
<p>You have @itemCount items in your cart.</p>
Rendered HTML
<h1>Welcome, Priya!</h1>
<p>You have 3 items in your cart.</p>

The @{ ... } block runs plain C# with no output; a bare @name or @itemCount inline in HTML outputs that expression's value, HTML-encoded automatically for safety.

Passing a model to a view

A controller action can return a view along with a strongly-typed model, which the view accesses through @model and Model:

C# Controllers/ProductsController.cs
public IActionResult Details(int id)
{
    var product = new Product { Id = id, Name = "Keyboard", Price = 49.99m };
    return View(product);
}
Razor Views/Products/Details.cshtml
@model Product

<h1>@Model.Name</h1>
<p>Price: $@Model.Price</p>
Rendered HTML
<h1>Keyboard</h1>
<p>Price: $49.99</p>

The @model Product line at the top of the view declares the type of Model for that file, giving you full IntelliSense and compile-time checking on @Model.Name and @Model.Price — a typo here fails at build time, not with a silent blank in the rendered page.

Loops and conditionals in Razor

Razor Views/Products/List.cshtml
@model List<Product>

<ul>
@foreach (var product in Model)
{
    <li>@product.Name — $@product.Price</li>
}
</ul>

@if (Model.Count == 0)
{
    <p>No products found.</p>
}
Rendered HTML, given two products
<ul>
<li>Keyboard — $49.99</li>
<li>Mouse — $19.99</li>
</ul>
Note: Razor auto-encodes anything output with @, so @product.Name containing <script> renders as harmless text, not executable HTML — an important default against XSS. If you ever genuinely need to output raw, unescaped HTML, that requires the explicit Html.Raw(...) helper, which you should only reach for with content you trust completely.