Komponenty Razor: jak działają dla programistów
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).

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.
Rozszerzalność
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

@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.

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. Na przykład w komponencie Razor można zdefiniować parametr w następujący sposób:
@code {
[Parameter]
public string Message { get; set; }
}
Następnie użyj parametru component w klasie Razor Component w następujący sposób:
<p>@Message</p>
I przekaż dane do komponentu z komponentu nadrzędnego w następujący sposób:
<MyComponent Message="Hello from parent component!" />
Komponenty Razor mogą również zawierać logikę po stronie serwera, którą można wykonać po stronie klienta. Na przykład można pisać logikę przetwarzania, wysyłać żądania HTTP, obsługiwać zdarzenia użytkownika i wykonywać inne operacje po stronie serwera bezpośrednio z komponentów Razor przy użyciu kodu C#. Pozwala to tworzyć dynamiczne i interaktywne strony internetowe bez pisania kodu JavaScript.
Tworzenie komponentów Razor wielokrotnego użytku
Jedną z zalet komponentów Razor jest możliwość tworzenia komponentów interfejsu użytkownika, które można wykorzystywać wielokrotnie na wielu stronach lub w wielu aplikacjach. Aby utworzyć komponent wielokrotnego użytku, można utworzyć nowy plik ".razor" w folderze "Shared" projektu.
Załóżmy na przykład, że chcemy stworzyć komponent wyświetlający listę książek. We can create a new BookList.razor file in the "Shared" folder such as:

Komponent Razor możemy zdefiniować w następujący sposób:
@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.
W następnej sekcji omówimy, jak używać IronPDF z komponentami Razor do tworzenia plików PDF z aplikacji internetowych.
Korzystanie z IronPDF z komponentami Razor
IronPDF to biblioteka C#, która pozwala programistom tworzyć pliki PDF z HTML, CSS i JavaScript. Jest oparty na Chromium, przeglądarce typu open source, na której działa Google Chrome. Dzięki IronPDF programiści mogą z łatwością konwertować komponenty Razor na HTML i tworzyć z nich pliki PDF.
IronPDF doskonale radzi sobie z konwersją HTML do PDF, zapewniając zachowanie układu i stylu. Jest to szczególnie przydatne do generowania plików PDF z treści internetowych, takich jak raporty, faktury i dokumentacja. 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");
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
' 1. Convert HTML String to PDF
Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
' 2. Convert HTML File to PDF
Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
' 3. Convert URL to PDF
Dim url = "http://ironpdf.com" ' Specify the URL
Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
pdfFromUrl.SaveAs("URLToPDF.pdf")
End Sub
End Class
Instalacja IronPDF
Aby korzystać z IronPDF z komponentami Razor, musimy najpierw zainstalować pakiet IronPDF NuGet. Aby to zrobić, wykonaj następujące kroki:
- Otwórz swój projekt w Visual Studio.
- Kliknij prawym przyciskiem myszy na projekt i wybierz "Zarządzaj pakietami NuGet".
- Wyszukaj "IronPDF" i wybierz "pakiet IronPDF".
- Kliknij "Zainstaluj", aby zainstalować pakiet.
Po zainstalowaniu pakietu IronPDF NuGet możemy używać go w naszej aplikacji Razor Components.

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. Załóżmy na przykład, że chcemy utworzyć plik PDF z przyrostem licznika.
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");
Dim renderer = New IronPdf.ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>My PDF #" & currentCount & "</h1>")
pdf.SaveAs("myPdf" & currentCount & ".pdf")
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.
W tym przykładzie zmodyfikowaliśmy nasz komponent licznika. We have modified the onClick function of a counter button that, when clicked, will create a PDF containing the count of the Counter.
Wnioski
W tym artykule omówiliśmy, jak używać komponentów Razor z IronPDF do tworzenia plików PDF z aplikacji internetowych. Omówiliśmy podstawy komponentów Razor, sposób instalacji i użytkowania IronPDF oraz podaliśmy przykłady kodu, które pomogą Ci rozpocząć pracę.
Razor Components i IronPDF to potężne narzędzia, które można wykorzystać do tworzenia solidnych i bogatych w funkcje aplikacji internetowych. Łącząc te technologie, programiści mogą tworzyć aplikacje internetowe, które są zarówno wysoce funkcjonalne, jak i atrakcyjne wizualnie.
IronPDF może być również używany do konwersji stron Razor i adresów URL do formatu PDF, a także do odczytu, tworzenia i edycji dokumentów PDF. IronPDF umożliwia nawet bardziej szczegółową kontrolę nad plikami PDF, taką jak dodawanie nagłówków, stopek, numerów stron, podpisów cyfrowych, haseł oraz zaawansowanych funkcji edycji do istniejących lub nowo utworzonych dokumentów PDF. Jest bezpłatny do celów programistycznych, ale do użytku produkcyjnego wymaga bezpłatnej licencji próbnej lub licencji komercyjnej.
Często Zadawane Pytania
Czym są komponenty Razor?
Komponenty Razor to framework interfejsu użytkownika w .NET Core, który pozwala programistom tworzyć strony internetowe przy użyciu kombinacji języków C# i HTML, z logiką po stronie serwera, która może być również wykonywana po stronie klienta. Są one częścią frameworka Blazor i obsługują architekturę opartą na komponentach.
W jaki sposób komponenty Razor usprawniają tworzenie stron internetowych?
Komponenty Razor upraszczają tworzenie stron internetowych, umożliwiając programistom korzystanie z języków C# i HTML do tworzenia dynamicznych i interaktywnych aplikacji internetowych bez konieczności stosowania JavaScript. Skutkuje to bardziej płynną integracją logiki po stronie serwera z interaktywnością po stronie klienta.
Jak wygenerować plik PDF z komponentów Razor?
Aby generować pliki PDF z komponentów Razor, można użyć IronPDF, który umożliwia konwersję wyjścia HTML z komponentów do formatu PDF. Osiąga się to za pomocą klasy IronPdf.ChromePdfRenderer, która renderuje komponenty do pliku PDF.
Jakie są zalety korzystania z komponentów Razor?
Komponenty Razor oferują szereg korzyści, w tym możliwość ponownego wykorzystania, modułowość, płynną integrację z językiem C#, wykonywanie po stronie serwera i klienta, komunikację w czasie rzeczywistym za pomocą SignalR oraz wysoką rozszerzalność.
Jak zainstalować IronPDF w moim projekcie?
Aby dodać IronPDF do swojego projektu, użyj menedżera pakietów NuGet w Visual Studio. Wyszukaj pakiet IronPDF i zainstaluj go, aby umożliwić generowanie plików PDF w komponentach Razor.
Czy komponenty Razor mogą działać zarówno po stronie serwera, jak i po stronie klienta?
Tak, komponenty Razor mogą działać zarówno po stronie serwera, jak i po stronie klienta, w zależności od wybranego modelu hostingu. Ta elastyczność pozwala programistom zoptymalizować wydajność i bezpieczeństwo aplikacji w oparciu o konkretne potrzeby projektu.
W jaki sposób komponenty Razor promują ponowne wykorzystanie?
Komponenty Razor sprzyjają ponownemu wykorzystaniu, ponieważ są samowystarczalne, co pozwala na ich użycie w wielu miejscach w ramach jednej aplikacji lub w różnych projektach. Ogranicza to powielanie kodu oraz poprawia łatwość konserwacji i skalowalność.
Jakie są przykłady zastosowań generowania plików PDF z treści internetowych?
Generowanie plików PDF z treści internetowych za pomocą IronPDF jest przydatne przy tworzeniu standardowych dokumentów, takich jak raporty, faktury i dokumentacja, zapewniając zachowanie układu i stylu treści na różnych platformach.
Jak mogę tworzyć niestandardowe elementy interfejsu użytkownika za pomocą komponentów Razor?
Możesz tworzyć niestandardowe elementy interfejsu użytkownika, definiując je w plikach „.razor” przy użyciu składni Razor. Pozwala to programistom łączyć C# i HTML, tworząc dynamiczne i wielokrotnego użytku komponenty dostosowane do konkretnych potrzeb aplikacji.
Jak działają parametry w komponentach Razor?
W komponentach Razor parametry służą do przekazywania danych z komponentów nadrzędnych do komponentów podrzędnych. Ułatwia to atrybut [Parameter], umożliwiający komunikację i wymianę danych między różnymi częściami aplikacji.




