푸터 콘텐츠로 바로가기
.NET 도움말

Razor C# (How It Works For Developers)

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

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

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>
$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;
$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.

자주 묻는 질문

C#에서 Razor를 사용하여 HTML에서 PDF를 생성하려면 어떻게 해야 하나요?

IronPDF 라이브러리를 사용하여 C#에서 Razor를 사용하여 HTML에서 PDF를 생성할 수 있습니다. 먼저 IronPDF 패키지를 설치하고 IronPDF 네임스페이스를 가져온 다음, RenderHtmlAsPdf와 같은 API 메서드를 사용하여 HTML 콘텐츠를 PDF 형식으로 변환합니다.

웹 개발에서 Razor 구문의 역할은 무엇인가요?

레이저 구문은 C# 또는 VB를 HTML과 결합하여 동적 웹 페이지를 생성함으로써 웹 개발에서 중요한 역할을 합니다. 이를 통해 개발자는 HTML이 클라이언트의 브라우저로 전송되기 전에 실행되는 서버 측 코드를 작성하여 원활한 통합과 기능을 촉진할 수 있습니다.

Razor Pages는 웹 애플리케이션 개발을 어떻게 향상시키나요?

Razor 페이지는 체계적이고 조직적인 코드 관리 방법을 제공하여 중복과 복잡성을 줄여 웹 애플리케이션 개발을 향상시킵니다. 개발자가 페이지 기반 형식 내에서 기능을 구축하는 데 집중할 수 있도록 하여 개발 프로세스를 간소화합니다.

태그 도우미란 무엇이며 Razor 페이지에서 어떻게 지원하나요?

Razor Pages의 태그 헬퍼는 서버 측 코드가 HTML과 유사한 구문으로 HTML 요소를 만들고 렌더링할 수 있도록 지원합니다. 이렇게 하면 클라이언트의 브라우저로 요소를 보내기 전에 서버에서 요소를 변환하여 깔끔하고 유지 관리하기 쉬운 HTML 마크업을 생성하는 데 도움이 됩니다.

Razor 페이지에서 사용자 상호 작용을 처리하려면 어떻게 해야 하나요?

Razor 페이지의 사용자 상호 작용은 OnPostAsync와 같은 핸들러 메서드를 사용하여 관리됩니다. 이러한 메서드는 양식 제출 및 기타 사용자 입력을 처리하여 개발자가 클라이언트로부터 받은 데이터를 기반으로 작업을 실행할 수 있도록 합니다.

Razor에서 '@model' 지시어의 의미는 무엇인가요?

Razor의 '@model' 지시어는 Razor 페이지에 전달되는 객체의 데이터 유형을 지정하기 때문에 중요합니다. 이를 통해 개발자는 페이지 내에서 직접 모델의 속성에 액세스하고 조작하여 데이터 바인딩 및 상호 작용을 용이하게 할 수 있습니다.

Visual Studio에서 C#과 함께 Razor를 사용하면 어떤 이점이 있나요?

Visual Studio에서 C#과 함께 Razor를 사용하면 서버 측 로직과 HTML의 통합, Razor 페이지를 통한 간소화된 개발, 동적 웹 콘텐츠를 쉽게 생성할 수 있는 기능 등의 이점을 누릴 수 있습니다. 또한 Visual Studio는 Razor 개발을 지원하는 강력한 도구와 템플릿을 제공합니다.

C#과 VB 모두에 Razor 구문을 사용할 수 있나요?

예, Razor 구문은 C#과 VB(Visual Basic) 모두에서 서버 측 로직을 HTML과 결합하는 데 사용할 수 있습니다. 이러한 유연성 덕분에 개발자는 선호하는 언어를 선택하면서 웹 개발에서 Razor의 기능을 활용할 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.