Saltar al pie de página
.NET AYUDA

Razor C# (Cómo funciona para desarrolladores)

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>
<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>
$vbLabelText   $csharpLabel

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>
$vbLabelText   $csharpLabel

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>
$vbLabelText   $csharpLabel

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>
$vbLabelText   $csharpLabel

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>
'}
$vbLabelText   $csharpLabel

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>
$vbLabelText   $csharpLabel

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>
<p>@("Hello World")</p>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<p> @("Hello World")</p>
$vbLabelText   $csharpLabel

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>
'}
$vbLabelText   $csharpLabel

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>
<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");
}
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
$vbLabelText   $csharpLabel

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 *@
$vbLabelText   $csharpLabel

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. *@
$vbLabelText   $csharpLabel

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 -->
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>
@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>
$vbLabelText   $csharpLabel

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:

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;
@using IronPdf;
Dim IronPdf As [using]
$vbLabelText   $csharpLabel

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);
    }
}

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.

Preguntas Frecuentes

¿Cómo puedo generar PDFs desde HTML usando Razor en C#?

Puedes generar PDFs desde HTML usando Razor en C# empleando la biblioteca IronPDF. Primero, instala el paquete de IronPDF, importa el espacio de nombres IronPDF y luego utiliza sus métodos de API como RenderHtmlAsPdf para convertir tu contenido HTML en formato PDF.

¿Cuál es el papel de la sintaxis Razor en el desarrollo web?

La sintaxis Razor juega un papel crucial en el desarrollo web al combinar C# o VB con HTML para crear páginas web dinámicas. Permite a los desarrolladores escribir código del lado del servidor que se ejecuta antes de que el HTML sea enviado al navegador del cliente, facilitando una integración y funcionalidad sin problemas.

¿Cómo mejoran las Razor Pages el desarrollo de aplicaciones web?

Las Razor Pages mejoran el desarrollo de aplicaciones web al proporcionar una manera estructurada y organizada de gestionar el código, reduciendo la duplicación y complejidad. Simplifican el proceso de desarrollo al permitir a los desarrolladores enfocarse en construir funcionalidad dentro de un formato basado en páginas.

¿Qué son los Tag Helpers y cómo asisten en las Razor Pages?

Los Tag Helpers en las Razor Pages asisten permitiendo que el código del lado del servidor cree y renderice elementos HTML con una sintaxis similar a HTML. Esto ayuda a producir un marcado HTML limpio y mantenible al transformar elementos en el servidor antes de enviarlos al navegador del cliente.

¿Cómo puedo manejar las interacciones de usuario en las Razor Pages?

Las interacciones de usuario en Razor Pages se gestionan usando métodos manejadores como OnPostAsync. Estos métodos procesan el envío de formularios y otras entradas del usuario, permitiendo a los desarrolladores ejecutar operaciones basadas en los datos recibidos de los clientes.

¿Cuál es la importancia de la directiva '@model' en Razor?

La directiva '@model' en Razor es significativa porque especifica el tipo de datos del objeto pasado a una página Razor. Esto permite a los desarrolladores acceder y manipular las propiedades del modelo directamente dentro de la página, facilitando la vinculación e interacción de datos.

¿Cuáles son los beneficios de usar Razor con C# en Visual Studio?

Usar Razor con C# en Visual Studio ofrece beneficios como la integración de la lógica del lado del servidor con HTML, desarrollo simplificado a través de Razor Pages y la capacidad de generar fácilmente contenido web dinámico. Además, Visual Studio proporciona herramientas y plantillas robustas para apoyar el desarrollo con Razor.

¿Puedo usar la sintaxis de Razor para ambos C# y VB?

Sí, la sintaxis de Razor puede ser utilizada con ambos C# y VB (Visual Basic) para combinar la lógica del lado del servidor con HTML. Esta flexibilidad permite a los desarrolladores elegir su lenguaje preferido mientras se benefician de las capacidades de Razor en el desarrollo web.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más