.NET HELP

Razor C# (How It Works For Developers)

Published May 30, 2023
Share:

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

Explore Razor Syntax in ASP.NET Core is a combination of HTML and server. 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 a simple Razor syntax:

<p>The current time is @DateTime.Now</p>
<p>The current time is @DateTime.Now</p>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<p> The current time is @DateTime.Now</p>
VB   C#

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>
@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>
page model ReadOnly Property () As IndexModel
	ViewData ("Title") = "Home page"
End Property

'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<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>
VB   C#

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>
<p>Hello, my name is @Model.Name</p>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<p> Hello, my name is @Model.Name</p>
VB   C#

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>
@{
    var name = "IronPDF";
}
<p>Hello, my name is @name</p>
@
If True Then
	Dim name = "IronPDF"
End If
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<p> Hello, my name is @name</p>
VB   C#

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>
}
@{
    var count = 5;
}

@if(count > 3){
    <p>The count is greater than 3.</p>
}
@
If True Then
	Dim count = 5
End If

'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'@if(count > 3)
'{
'	<p> The count is greater than 3.</p>
'}
VB   C#

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>
@{
    var fileFormat = "PDF";
    var message = "";

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

<p>@message</p>
@
If True Then
	Dim fileFormat = "PDF"
	Dim message = ""

	Select Case fileFormat
		Case "PDF"
			message = "You selected PDF."
		Case Else
			message = "Invalid selection."
	End Select
End If

'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<p> @message</p>
VB   C#

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 below example:

<p>@("Hello World")</p>
<p>@("Hello World")</p>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<p> @("Hello World")</p>
VB   C#

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>
}
@{
    var names = new List<string>{"John", "Doe", "Smith"};
}

@foreach(var name in names)
{
    <p>@name</p>
}
@
If True Then
	Dim names = New List(Of String) From {"John", "Doe", "Smith"}
End If

'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'@foreach(var name in names)
'{
'	<p> @name</p>
'}
VB   C#

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 they 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>
<a asp-controller="Home" asp-action="Index">Home</a>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<a asp-controller="Home" asp-action="Index"> Home</a>
VB   C#

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 method 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");
}
public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }

    // Perform some operation here

    return RedirectToPage("./Index");
}
Public Async Function OnPostAsync() As Task(Of IActionResult)
	If Not ModelState.IsValid Then
		Return Page()
	End If

	' Perform some operation here

	Return RedirectToPage("./Index")
End Function
VB   C#

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 *@
@* This is a Razor comment *@
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'@* This is a Razor comment *@
VB   C#

And this is a multi-line comment:

@*
    This is a multi-line Razor comment.
    It's useful when you have a lot to say.
*@
@*
    This is a multi-line Razor comment.
    It's useful when you have a lot to say.
*@
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'@* This is a multi-line Razor comment.It's useful @when you have a lot @to say. *@
VB   C#

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 -->
<!-- This is an HTML comment -->
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<!-- This is an HTML comment -- >
VB   C#

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 below example:

@page
@model ExampleModel

<h2>@Model.Title</h2>
<p>@Model.Description</p>
@page
@model ExampleModel

<h2>@Model.Title</h2>
<p>@Model.Description</p>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'@page @model ExampleModel <h2> @Model.Title</h2> <p> @Model.Description</p>
VB   C#

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:

:PackageInstall

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;
@using IronPdf;
Dim IronPdf As [using]
VB   C#

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);
    }
}
@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);
    }
}
Private page "/pdf" [using] IronPdf
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: 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
"btn btn-primary mt-3" onclick="CreatePDF"> Create PDF</button> </div> code
Private Friend IJSRuntime As inject
	Private Property htmlString() As String

	Private Async Function CreatePDF() As Task

		Dim Renderer = New IronPdf.ChromePdfRenderer()
		Renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A2

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

		Dim Content = New DotNetStreamReference(stream:= doc.Stream)

		Await JS.InvokeVoidAsync("SubmitHTML", "ironpdf.pdf", Content)
	End Function
End Class
VB   C#

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.

< PREVIOUS
Vim For Windows (How it Works for Developers)
NEXT >
C# Wait For Seconds (How it Works for Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,781,565 View Licenses >