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

Razor Components : How it Works for Developers

Web development has come a long way over the years, and with the advent of modern frameworks and libraries, developers have access to powerful tools for building dynamic and interactive web pages. One such technology that has gained significant popularity in recent years is Razor Components, which is part of the Blazor framework in ASP.NET Core. Razor Components allow developers to build rich, client-side web applications using C# and HTML, without having to write JavaScript. In this article, we will look at Razor Components and how they can be used to create modular, reusable, and dynamic web pages.

What are Razor Components

Razor Components are a UI framework in ASP.NET Core that allows developers to build web pages using a combination of C# and HTML, with the ability to write server-side logic that can be executed on the client side. Razor Components are part of the Blazor framework, which is a client-side web UI framework that runs C# code in the browser using WebAssembly (Wasm) or SignalR. Razor Components provide a component-based architecture for building modern web applications, where the UI is broken down into smaller, self-contained components that can be composed together to create a complete web page.

Razor Components use a markup language called Razor syntax, which is a combination of C# and HTML that allows for seamless integration of server-side and client-side code. Razor Components are similar to other component-based UI frameworks, such as React, Angular, and Vue, but with the key difference that they are written in C# and run on the server or client side, depending on the hosting model (WebAssembly or SignalR).

Razor Components : How It Works For Developers: Figure 2 - What is Blazor and what is Razor Components?

Benefits of Razor Components

Razor Components offer several benefits for web developers, including:

Reusability

Razor Components are self-contained elements that can be easily reused in multiple places within a web application or across different projects. This promotes code reusability and reduces code duplication, resulting in more maintainable and scalable web applications.

Modularity

Razor Components follow a component-based architecture, where the UI is broken down into smaller components that can be composed together to create complex web pages. This promotes modularity, allowing developers to encapsulate UI and logic within individual components, making it easier to manage and maintain the codebase.

Seamless Integration with C#

Since Razor Components are written in C#, developers can leverage their existing C# skills and knowledge to build web applications. This eliminates the need to learn and write JavaScript, which can be a significant advantage for developers who are already familiar with C#.

Server-Side and Client-Side Execution

Razor Components can be executed either on the server or client side, depending on the hosting model. This gives developers flexibility in choosing the most appropriate execution model for their application, depending on factors such as performance, security, and user experience.

Real-time Communication

Razor Components can use SignalR, a real-time communication library, to establish bi-directional communication between the client and server. This enables real-time updates and notifications in web applications, providing a responsive and interactive user experience.

Extensibility

Razor Components are highly extensible, allowing developers to create their custom components, libraries, and templates. This enables developers to build tailored solutions that meet the specific requirements of their web applications.

Getting Started with Razor Component

To get started with Razor Components, you will need to have .NET Core 3.0 or later installed on your system. Create a new ASP.NET Core project using the Blazor template in Visual Studio or the .NET Core CLI.

dotnet new blazorserver

Razor Components : How It Works For Developers: Figure 3

@page "/counter"

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>
<button @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

In this example, we have a Razor component called "Counter" with a button that increments the currentCount variable when clicked. The @code block is used to define the C# code for the component.

Razor Components : How It Works For Developers: Figure 4

Create a Custom Razor Component

In the project, create a new folder called "Components" to store your Razor Components.

Inside the "Components" folder, add a new Razor Component file with the ".razor" extension. This file will contain the C# and HTML code for your component.

Open the Razor Component file and define your component using Razor syntax. Razor syntax allows you to combine C# and HTML code in a single file, making it easy to create dynamic web pages. For example, you can define a simple Razor Component like this:

<h1>Hello, World!</h1>
<p>This is a Razor Component.</p>

@code {
    // C# code for the component can be added here
}

You can now use your Razor Component in other parts of your web application by including it in your HTML markup using the component's tag name. For example, you can use the component in your main Razor page like this:

<MyComponent />

You can also pass data to your Razor Component using component parameters. Component parameters allow you to pass data from a parent component to a child component, enabling communication between components. For example, you can define a parameter in your Razor Component like this:

@code {
    [Parameter]
    public string Message { get; set; }
}

And then use the component parameter in your Razor Component class like this:

<p>@Message</p>

And pass data to the component from a parent component like this:

<MyComponent Message="Hello from parent component!" />

Razor Components can also contain server-side logic that can be executed on the client side. For example, you can write processing logic, make HTTP requests, handle user events, and perform other server-side operations directly from your Razor Components using C# code. This allows you to create dynamic and interactive web pages without writing any JavaScript code.

Creating Reusable Razor Components

One of the benefits of Razor Components is the ability to create reusable UI components that can be used across multiple pages or applications. To create a reusable component, you can create a new ".razor" file in the "Shared" folder of your project.

For example, let's say we want to create a component that displays a list of books. We can create a new BookList.razor file in the "Shared" folder such as:

Razor Components : How It Works For Developers: Figure 5 - Generated class

We can define the razor component like this:

@typeparam TItem

@foreach (var book in Books)
{
    <p>@book.Title by @book.Author</p>
}

@code {
    [Parameter]
    public List<TItem> Books { get; set; }
}

In this example, we have a component called BookList that takes a list of "Book" objects as a razor parameter. The @foreach loop is used to iterate through the list and display each book title and author.

In the next section, we will explore how to use IronPDF with Razor Components to create PDF files from web applications.

Using IronPDF with Razor Components

IronPDF is a C# library that allows developers to create PDF files from HTML, CSS, and JavaScript. It is built on top of Chromium, the open-source browser that powers Google Chrome. With IronPDF, developers can easily convert Razor Components to HTML and create PDF files from them.

IronPDF excels at converting HTML to PDF, ensuring that the layout and style remain intact. This is particularly useful for generating PDFs from web-based content like reports, invoices, and documentation. HTML files, URLs, and HTML strings can be easily converted into PDF files.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
$vbLabelText   $csharpLabel

Installing IronPDF

To use IronPDF with Razor Components, we first need to install the IronPDF NuGet package. To do this, follow these steps:

  1. Open your project in Visual Studio.
  2. Right-click on the project and select "Manage NuGet Packages".
  3. Search for "IronPDF" and select the "IronPDF package".
  4. Click on "Install" to install the package.

After installing the IronPDF NuGet package, we can use it in our Razor Components application.

Razor Components : How It Works For Developers: Figure 6

Once the package is installed, you can create a new PDF file from a Razor Component by using the IronPdf.ChromePdfRenderer class.

To create a PDF file in ASP.NET Core Razor Components, you can pass the HTML syntax string, HTML File, or URL to the IronPdf.ChromePdfRenderer method. For example, let's say we want to create a PDF file with the increment of a counter.

var renderer = new IronPdf.ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>My PDF #" + currentCount + "</h1>");
pdf.SaveAs("myPdf" + currentCount + ".pdf");
var renderer = new IronPdf.ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>My PDF #" + currentCount + "</h1>");
pdf.SaveAs("myPdf" + currentCount + ".pdf");
$vbLabelText   $csharpLabel

In this example, we create a new instance of the ChromePdfRenderer. We then create a new instance of the PdfDocument class and pass a string to the RenderHtmlAsPdf method. Finally, we save the resulting PDF file to disk using the PdfDocument.SaveAs method.

In this example, we have modified our counter component. We have modified the onClick function of a counter button that, when clicked, will create a PDF containing the count of the Counter.

Conclusion

In this article, we have explored how to use Razor Components with IronPDF to create PDF files from web applications. We have covered the basics of Razor Components, how to install and use IronPDF, and provided code examples to help you get started.

Razor Components and IronPDF are powerful tools that can be used to create robust and feature-rich web applications. By combining these technologies, developers can create web applications that are both highly functional and visually appealing.

IronPDF can also be used to convert razor pages and URLs to PDFs, as well as to read, create and manipulate PDF documents. IronPDF even allows for more granular PDF control such as adding headers, footers, page numbers, digital signatures, passwords, and advanced PDF manipulation features to existing or newly generated PDF documents. It is free for development but requires a free trial license or commercial license for production.

자주 묻는 질문

Razor 컴포넌트란 무엇인가요?

레이저 컴포넌트는 개발자가 클라이언트 측에서도 실행할 수 있는 서버 측 로직과 함께 C#과 HTML의 조합을 사용하여 웹 페이지를 구축할 수 있는 ASP.NET Core의 UI 프레임워크입니다. Blazor 프레임워크의 일부이며 컴포넌트 기반 아키텍처를 지원합니다.

Razor 컴포넌트는 웹 개발을 어떻게 향상시키나요?

Razor 컴포넌트는 개발자가 자바스크립트에 의존하지 않고도 C#과 HTML을 사용하여 동적인 대화형 웹 애플리케이션을 만들 수 있도록 함으로써 웹 개발을 간소화합니다. 그 결과 서버 측 로직과 클라이언트 측 상호 작용을 보다 원활하게 통합할 수 있습니다.

Razor 컴포넌트에서 PDF를 생성하려면 어떻게 해야 하나요?

Razor 컴포넌트에서 PDF를 생성하려면 컴포넌트의 HTML 출력을 PDF 형식으로 변환할 수 있는 IronPDF를 사용하면 됩니다. 이 작업은 IronPdf.ChromePdfRenderer 클래스를 사용하여 컴포넌트를 PDF 파일로 렌더링하는 방식으로 이루어집니다.

Razor 컴포넌트를 사용하면 어떤 이점이 있나요?

Razor 컴포넌트는 재사용성, 모듈성, C#과의 원활한 통합, 서버 측 및 클라이언트 측 실행, SignalR과의 실시간 커뮤니케이션, 높은 확장성 등 여러 가지 이점을 제공합니다.

프로젝트에 IronPDF를 설치하려면 어떻게 해야 하나요?

프로젝트에 IronPDF를 추가하려면 Visual Studio의 NuGet 패키지 관리자를 사용하세요. IronPDF 패키지를 검색하여 설치하면 Razor 컴포넌트 내에서 PDF 생성 기능을 활성화할 수 있습니다.

Razor 컴포넌트는 서버 측과 클라이언트 측 모두에서 실행할 수 있나요?

예, Razor 컴포넌트는 선택한 호스팅 모델에 따라 서버 측과 클라이언트 측 모두에서 실행할 수 있습니다. 이러한 유연성 덕분에 개발자는 특정 프로젝트 요구 사항에 따라 애플리케이션 성능과 보안을 최적화할 수 있습니다.

Razor 컴포넌트는 어떻게 재사용성을 촉진하나요?

Razor 컴포넌트는 독립형이기 때문에 애플리케이션 내 여러 위치에서 또는 여러 프로젝트에 걸쳐 사용할 수 있어 재사용성을 높입니다. 이를 통해 코드 중복을 줄이고 유지 관리 및 확장성을 향상시킬 수 있습니다.

웹 콘텐츠에서 PDF를 생성하는 사용 사례에는 어떤 것이 있나요?

IronPDF를 사용하여 웹 콘텐츠에서 PDF를 생성하면 보고서, 송장, 문서와 같은 표준화된 문서를 생성하여 다양한 플랫폼에서 콘텐츠의 레이아웃과 스타일을 유지하는 데 유용합니다.

Razor 컴포넌트로 사용자 지정 UI 요소를 만들려면 어떻게 해야 하나요?

Razor 구문을 사용하여 '.razor' 파일에 정의하여 사용자 지정 UI 요소를 만들 수 있습니다. 이를 통해 개발자는 C#과 HTML을 혼합하여 특정 애플리케이션 요구 사항에 맞는 동적이고 재사용 가능한 구성 요소를 만들 수 있습니다.

Razor 컴포넌트에서 매개변수는 어떻게 작동하나요?

Razor 컴포넌트에서 매개변수는 부모 컴포넌트에서 자식 컴포넌트로 데이터를 전달하는 데 사용됩니다. 이는 [Parameter] 속성을 통해 이루어지며, 애플리케이션의 여러 부분 간에 통신 및 데이터 공유를 가능하게 합니다.

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

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

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