Exploring ASP.Net Razor: Putting C# in your HTML

With Razor Microsoft puts server-side code and web design on the same page

Exploring ASP.Net Razor: Putting C# in your HTML
Hitesh Choudhary (CC0)

Microsoft’s Active Server Pages have been around a long time; launching back in the early days of the web. Since then they’ve been through several iterations and frameworks, driving the development of ASP.Net and now ASP.Net Core. A focus on the model-view-controller (MVC) design pattern has kept them relevant, with the latest generation of the platform now an open source project.

ASP.Net Core is a redesign of the popular ASP.Net 4 framework, rebuilt for the open .Net Core framework and ideal for use in Windows container microservices hosted in Windows Server Nano. Lightweight and fast, it’s quick to deploy and works well as part of a modern cloud-hosted application architecture. You’re not limited to Microsoft’s own IIS web server either, as the latest versions host on Linux as well as Windows, and run in Apache and Nginx.

A key component of ASP.Net Core is the ASP.Net Core MVC presentation. It’s a quick way to build complex web front ends, with a routing schema that constructs URLs for applications that describe actions, and model binding that maps data to objects, simplifying how your application works with data in web views. Much of ASP.Net MVC builds on more than 20 years of web application development experience, making it familiar to those of us who’ve used it all that time, yet still easy to pick up if you’re new to building web apps.

Introducing Razor

One of the more important elements of ASP.Net Core is the Razor markup syntax. I’ve touched on it in the past when writing about Microsoft Web Assembly tool Blazor, which uses Razor syntax, but it’s worth drilling into it in more detail, as its mix of C# and HTML gives you a useful way to render dynamic web content on a server.

Originally introduced with Microsoft’s now discontinued WebMatrix web development tools, Razor builds on the original VBScript ASP model, with embedded scripting code in web page content. Like any web page, Razor content starts with HTML, adding C# code and using a .cshtml file extension. Embedded Razor commands and C# code is indicated with an @ symbol (so if you want to use an @ in your Razor HTML, use the symbol twice: @@). The Razor parser is smart enough to recognize the @ in an email address, so there’s no need to add a second one.

Working with Razor and C#

The Razor engine is an embedded REPL (read-eval-print loop), working like an in-editor REPL to evaluate in-line C# code and replace it with the appropriate result. Some Razor code will be snippets of program, handling loops and conditionals; others will be simple implicit C# expressions. There’s no need to write lots of code to print the date in a Razor page when all you need is the C# expression @DateTime.now.

Similarly you can use @( ) to wrap explicit C# expressions where a simple statement is evaluated at run time and the result displayed in place of the Razor code block. Using a mix of implicit and explicit C# you can build basic page templates that mix HTML and C#, giving you the basic components of an MVC application’s view.

Code blocks: conditionals and loops

But simple expressions are only part of Razor; much of its power comes from embedding blocks of code on the page, using the familiar {} to wrap a code block. Much like we did with VBScript in the old days of the original ASP, you can embed code to dynamically generate more complex HTML content. As Razor is parsed like HTML, there’s an implicit order to how code is rendered in your pages, evaluating code blocks and expressions from the top of the page down.

Code blocks are the best way of handling conditionals and other control structures inside Razor. You can start a line with, say, @if, add a condition, and then a code block that runs if that condition is met. Similarly we can continue with else if and else statements; since we’ve started our Razor block with @if there’s no need to add @ in front of these statements (Razor treats it as one @if … else if … else block).

Under the hood the server-side ASP.Net Core engine takes your Razor code and uses it to generate C# classes that run and deliver content as part of your HTML pages. This approach allows them to implement what Razor calls directives, which control how pages are rendered and how they use C# code. For example, Razor’s directives include @model, which controls the model that’s passed to a view and gives access to its properties.

Building page templates in Razor

One useful Razor feature is the <text> tag. When included in a code block, the <text> tag wraps content that needs to be rendered in HTML. You might have a loop that iterates through an array that contains the contents of a catalog. By using <text> blocks inside the loop, you can format and display catalog contents without having to build complex HTML structures to host the content. This approach works well with Razor’s templated delegates, which can be used to define snippets of UI code that are loaded into pages on demand. Templates can also be included inline in your Razor code, simplifying page development but reducing code reuse and portability.

With many server-side application frameworks, commenting is a problem, as comments are usually rendered in the HTML. With Razor you can have a mix of Razor comments using C# syntax and HTML comments. C# comments are only visible to developers and aren’t passed on the browsers. However HTML comments are, so you can use the two commenting techniques for user-facing comments and debugging, and for developers.

There are plenty of tools for Razor in Visual Studio’s ASP.Net Core support. You’ll find tools for building and testing pages, as well as creating models and mapping those to page content. Built-in scaffolding tools will construct pages from the underlying Entity Framework, making it easier to link data to your code and giving you a page structure that can be customized using familiar web design tools. At the code level, tying Razor to ASP.Net Core’s MVC services simplifies building server-side C# to manage the model, with Razor delivering the view.

For those of us who’ve been building web apps on Microsoft platforms since the very beginning, Razor offers a familiar way to access new technologies, building on old skill sets to explore new technologies. For those coming to the platform fresh, it’s a relatively quick on-ramp into ASP.Net Core’s MVC application model, reducing the risks of error and simplifying the development of dynamic HTML content. That all adds up to a platform that’s well worth using across all your web properties.

Copyright © 2019 IDG Communications, Inc.