What Is the Razor View Engine?
Razor is the default view engine in ASP.NET MVC, replacing the older Web Forms (.aspx) engine. A Razor view file uses the .cshtml extension and mixes plain HTML markup with inline C# code using the @ symbol as a transition character. At request time, the ASP.NET runtime compiles each .cshtml file into a C# class that derives from WebViewPage<TModel> (classic MVC) or RazorPage<TModel> (ASP.NET Core), and that class's Execute() method runs to produce the final HTML sent to the browser.
Cricket analogy: Just as a scorer converts raw ball-by-ball notes into a formatted scorecard before it's displayed on the stadium screen, Razor converts a .cshtml template's mixed markup into a compiled C# class before it ever reaches the browser.
Razor Syntax: The @ Symbol
The @ symbol is Razor's single transition character between HTML and C#. A single @ followed by an expression, such as @Model.Name or @DateTime.Now, is evaluated inline and its result is written into the output. A multi-statement code block is wrapped in @{ ... }, which lets you declare variables, call methods, or run logic without producing output directly; no explicit closing tag is required because Razor's parser infers where C# ends and HTML resumes based on indentation and brace matching.
Cricket analogy: Like the umpire's single raised finger signaling out versus the longer sequence of signals for a no-ball, a single @Expression is a quick inline signal while @{ } blocks are the longer multi-step routine of overs bowled in sequence.
@model MyApp.Models.ProductViewModel
<h1>@Model.Name</h1>
@{
var discountLabel = Model.Price < 20 ? "Budget" : "Premium";
ViewBag.Title = Model.Name;
}
<p>Category: @Model.Category (@discountLabel)</p>
@if (Model.InStock)
{
<span class="badge badge-success">In Stock</span>
}
else
{
<span class="badge badge-danger">Out of Stock</span>
}
<ul>
@foreach (var review in Model.Reviews)
{
<li>@review.Author: @review.Rating / 5</li>
}
</ul>
@Html.ActionLink("Back to Catalog", "Index", "Products")Implicit vs Explicit Expressions
An implicit expression like @Model.Title works when Razor's parser can unambiguously determine where the C# expression ends, typically at whitespace or a markup character. When an expression is more complex or sits next to text that could be misread as part of it, such as @(2024 + 1) inside a sentence like "Copyright @(2024 + 1)", you must wrap it in parentheses as an explicit expression so Razor evaluates the arithmetic rather than concatenating literal text.
Cricket analogy: Like the difference between an obvious boundary that needs no third-umpire review versus a close run-out call that must be sent upstairs for explicit confirmation, implicit expressions are the clear calls and @(...) is the explicit review.
Automatic HTML Encoding and Html.Raw
Every value written through an @ expression is HTML-encoded automatically, meaning characters like <, >, and & are converted to their entity equivalents before being written to the response. This is Razor's default defense against cross-site scripting (XSS): if a user's comment contains <script>, it renders as visible text rather than executing. When you genuinely need to emit unescaped markup, such as HTML generated by a trusted CMS field, you call Html.Raw(Model.Content) to bypass encoding explicitly.
Cricket analogy: Like a boundary rope that keeps every hit ball contained within the field unless a fielder deliberately lifts it over, Razor's automatic encoding contains every value safely unless you deliberately call Html.Raw to let it through unescaped.
Never pass user-supplied input directly to Html.Raw(). Doing so reintroduces the cross-site scripting vulnerability that Razor's automatic encoding was designed to prevent. Reserve Html.Raw() strictly for content you control or that has already been sanitized on the server, such as HTML produced by a trusted markdown renderer.
Compilation and Performance
Razor views are compiled into .NET assemblies rather than interpreted line by line on every request. In classic ASP.NET MVC, the first request to a given view triggers just-in-time compilation, which is cached until the .cshtml file changes; in production, enabling precompiled views (via MvcBuildViews or Razor Class Libraries in ASP.NET Core) eliminates that first-request compilation delay entirely by compiling all views at build or publish time.
Cricket analogy: Like a team practicing net sessions before the actual match so the first real ball bowled isn't the first time a batter has faced that bowler, precompiling views avoids the 'first request' slowdown of just-in-time compilation.
In classic ASP.NET MVC, check the 'Enable Precompiled Views' setting or add <MvcBuildViews>true</MvcBuildViews> to your .csproj to catch view compilation errors at build time rather than at runtime. This surfaces typos in @Model references during your CI build instead of in production.
- Razor (.cshtml) is the default MVC view engine; the @ symbol is its single HTML-to-C# transition character.
- Views compile into classes derived from WebViewPage<TModel> or RazorPage<TModel> and run via an Execute() method.
- Implicit expressions (@Model.Name) work for simple, unambiguous cases; explicit expressions @(...) disambiguate complex ones.
- @ expressions are HTML-encoded automatically to prevent XSS; Html.Raw() explicitly bypasses that encoding.
- Never call Html.Raw() on unsanitized user input — it reopens the XSS hole Razor's encoding closes by default.
- Precompiling views (MvcBuildViews or build-time compilation) removes first-request JIT compilation delay and catches errors earlier.
Practice what you learned
1. What class does a compiled Razor view typically derive from in classic ASP.NET MVC?
2. What does Razor do by default to the output of an @ expression?
3. Which syntax should be used to disambiguate a complex expression like adding to a literal year in surrounding text?
4. When is it appropriate to use Html.Raw()?
5. What is the main benefit of precompiling Razor views?
Was this page helpful?
You May Also Like
HTML Helpers
Learn how HtmlHelper extension methods generate form controls, links, and validation markup in Razor views, and how they differ from raw HTML.
Layouts and Partial Views
Learn how _Layout.cshtml provides a shared page shell via RenderBody/@RenderSection, and how partial views let you reuse smaller markup fragments across views.
Strongly Typed Views
Learn how the @model directive binds a Razor view to a specific C# class, enabling IntelliSense, compile-time checking, and clean use of lambda-based helpers.
ViewBag, ViewData, and TempData
Compare the three loosely typed ways ASP.NET MVC passes data from controllers to views and across redirects, and when each one is appropriate.
Related Reading
Related Study Notes in Microsoft Technologies
Browse all study notesWindows 10 / UWP Development Study Notes
.NET · 30 topics
Microsoft TechnologiesWindows Batch Scripting Study Notes
Batch · 30 topics
Microsoft TechnologiesMFC (Microsoft Foundation Classes) Study Notes
C++ · 30 topics
Microsoft TechnologiesSilverlight Study Notes
.NET · 30 topics
Microsoft TechnologiesXAML Study Notes
.NET · 30 topics
Microsoft TechnologiesWPF (Windows Presentation Foundation) Study Notes
.NET · 30 topics