IRONSOFTWAREHOME
.NET HELP

Razor C# (How It Works For Developers)

Jacob Mellor, Chief Technology Officer @ Team Iron
Jacob Mellor
Updated: April 21, 2026

Razor is a server-side markup language used for creating dynamic web pages with the .NET Core and .NET Framework. It's primarily used in conjunction with ASP.NET Core. Razor Pages are a new aspect of ASP.NET Core that provide a clean and straightforward way to organize code within applications, reducing the problem of code duplication. Razor combines server-side using C# or VB (Visual Basic) with HTML to create web content.

This tutorial will guide you through creating a basic application using Razor with C# in Visual Studio. Let's begin!

Prerequisites

Before we dive into the world of Razor, ensure you have the following installed:

  1. .NET Core SDK
  2. Visual Studio

These are necessary as they provide the Razor View Engine and the project templates we'll be using for this tutorial. Also, they can operate on multiple operating systems, meaning you can follow along no matter if you are on Windows, Linux, or macOS.

Step 1 Creating a New Razor Pages Project

Open Microsoft Visual Studio and follow these steps:

  1. Click on "File" > "New" > "Project".

  2. In the project template selection screen, choose "Blazor Server App".

    Razor C# (How It Works For Developers) Figure 1

  3. Name your project "IronPDFExample" and click "Create".

    Razor C# (How It Works For Developers) Figure 2

  4. Select ".NET 7.0" or later from the dropdowns.

    Razor C# (How It Works For Developers) Figure 3

You now have a new Razor Pages project.

Understanding Razor Syntax and Files

Razor files use the .cshtml file extension, combining C# (hence the 'cs') with HTML. If we were using Visual Basic, the file extension would change to .vbhtml.

In your Solution Explorer, find and open the .cshtml extension file named "Index.cshtml". It's here you'll see a combination of HTML code and C# code. This mixing is made possible by the Razor Parser.

Razor Syntax

Razor Syntax in ASP.NET Core is a combination of HTML and server-side code. The server code is either C# or VB code. Razor code is denoted by the @ symbol, and it's executed on the server before the HTML is sent to the client.

An example of simple Razor syntax:

<p>The current time is @DateTime.Now</p>

In this code example, @DateTime.Now is a Razor code. It gets executed on the server, replaced with the current date and time before it's sent to the client.

Razor View

The term "view" in Razor corresponds to any webpage that's intended to present information to the user. The Razor View Engine is responsible for rendering the HTML page to the user.

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

Using Razor Markup for Dynamic Content

Razor Markup allows us to insert server-side code within our HTML markup. We can use various code constructs like code blocks, inline expressions, and HTML encoded expressions.

Inline Expression

An inline expression outputs the result directly to the HTML using the following code:

<p>Hello, my name is @Model.Name</p>

Here, @Model.Name is an inline expression that outputs the Name property's value from the model passed to the Razor view.

Code Block

Code blocks are segments of code that are run on the server:

@{
    var name = "IronPDF";
}
<p>Hello, my name is @name</p>

In this code example, the Razor code between { } is a code block.

Control Structures

We can also use control structures such as if-statements and loops in our Razor Pages:

@{
    var count = 5;
}

@if (count > 3)
{
    <p>The count is greater than 3.</p>
}

In the above code example, the if statement is part of the server-side code that runs on the server, and its output is inserted into the resulting HTML page.

Switch Statement

Switch statements are a type of conditional control structure in the C# programming language. They can be used within code blocks.

@{
    var fileFormat = "PDF";
    var message = "";

    switch (fileFormat) 
    {
        case "PDF":
            message = "You selected PDF.";
            break;
        default:
            message = "Invalid selection.";
            break;
    }
}

<p>@message</p>

Hello World in Razor

One of the simplest programs in any programming language is "Hello World". In Razor, you can display "Hello World" with a simple inline expression as shown in the example below:

<p>@("Hello World")</p>

Loops in Razor

Razor syntax allows you to write loops, such as the foreach statement. Suppose you have a list of names you want to display on your web page. You can achieve that with the foreach statement in Razor syntax.

@{
    var names = new List<string> { "John", "Doe", "Smith" };
}

@foreach (var name in names)
{
    <p>@name</p>
}

This foreach statement loops over each name in the list and outputs it to the web page.

Understanding Tag Helpers

Tag Helpers in ASP.NET MVC enable server-side code to create and render HTML elements in Razor files. They're a bit like HTML helpers but have a more HTML-like syntax. They transform HTML-like elements in your Razor views into the HTML markup sent to the client's browser. Consider the following code example of an anchor Tag Helper:

<a asp-controller="Home" asp-action="Index">Home</a>
HTML

Handling User Interaction

Razor Pages use handler methods to manage user interactions. For example, to handle form submission, we can create a method named OnPostAsync in our Razor Page's corresponding Page Model file.

public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }

    // Perform some operation here

    return RedirectToPage("./Index");
}

Comments in Razor

Razor also supports C# style comments. Remember, Razor comments are server-side, meaning they are not sent to the browser. They look like this:

@* This is a Razor comment *@

And this is a multi-line comment:

@*
    This is a multi-line Razor comment.
    It's useful when you have a lot to say.
*@

Razor views and pages can include HTML comments. These comments are visible in the HTML output sent to the browser.

<!-- This is an HTML comment -->
HTML

Passing Models to a Razor Page

Razor allows you to pass models to the page from the server. The @model directive is used to specify the type of object being passed. This model property can be accessed in the Razor page as shown in the example below:

@page
@model ExampleModel

<h2>@Model.Title</h2>
<p>@Model.Description</p>

Generating PDFs with IronPDF in Razor

Discover IronPDF for .NET is a popular library that allows developers to generate PDFs from HTML, images, and even existing web pages in .NET. It is an excellent tool for creating reports, invoices, and any other document where a standard print format is required. IronPDF works perfectly within the ASP.NET MVC and ASP.NET Razor Pages framework.

Installation

First, you need to install the IronPDF package. You can do this from the NuGet Package Manager Console in Visual Studio. Run the following command:

PM > Install-Package IronPdf

Creating a Simple PDF

Now, let's create a simple PDF from HTML code within your Razor Page. First, let's import the IronPDF namespace at the top of your Razor page.

@using IronPdf;

Then, you can use IronPDF to create a PDF. Let's say we have a button on our Razor page that will create a simple PDF when clicked.

In the corresponding handler in our Page Model file, we can add the following code:

@page "/pdf"
@using IronPdf;
@inject IJSRuntime JS

<PageTitle>Create PDF</PageTitle>

<h1>Create PDF</h1>

<div class="form-outline">
    <button class="btn btn-primary mt-3" @onclick="CreatePDF">Create PDF</button>
</div>

@code {
    private string htmlString { get; set; }

    private async Task CreatePDF()
    {
        var Renderer = new IronPdf.ChromePdfRenderer();
        Renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A2;

        var doc = Renderer.RenderUrlAsPdf("https://ironpdf.com/");

        using var Content = new DotNetStreamReference(stream: doc.Stream);

        await JS.InvokeVoidAsync("SubmitHTML", "ironpdf.pdf", Content);
    }
}
Text

OUTPUT

Razor C# (How It Works For Developers) Figure 4

Razor C# (How It Works For Developers) Figure 5

Conclusion

You have successfully learned the basics of Razor C# and discovered how to integrate IronPDF to generate PDF files within your application. You started by creating a new project in Visual Studio and then learned how to use Razor syntax to create dynamic web pages. You also explored how IronPDF can be used to generate PDFs from HTML code and even complete Razor Views.

Now, as you continue to build more advanced applications, you can take advantage of the powerful features offered by IronPDF. You can try IronPDF for free and if you find it valuable, you can purchase a license suitable for your needs.

Jacob Mellor, Chief Technology Officer @ Team Iron
Chief Technology Officer

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.

...
Read More

Related Articles

Key in blue circle

Get your free 30-day Trial Key instantly.

Your trial license will be sent to your email address

No limitations. 100% unlocked. No credit card.

OR
bullet_checkedNo credit card or account creation requiredNo limitations. 100% unlocked. No credit card.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried Iron Suite
Book your free Live Demo
Booking Badge

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required
C# NuGet Library for PDF
Install with NuGet

Version: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. In Solution Explorer, right-click References, Manage NuGet Packages
  2. Select Browse and search "IronPdf"
  3. Select the package and install
C# PDF DLL
Download DLL

Version: 2026.9

or download Windows Installer here.

  1. Download and unzip IronPDF to a location such as ~/Libs within your Solution directory
  2. In Visual Studio Solution Explorer, right click References. Select Browse, "IronPdf.dll"

Licenses from $999