Zum Fußzeileninhalt springen
.NET HILFE

Razor-Komponenten : Wie es für Entwickler funktioniert

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");
    }
}
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
$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");
Dim renderer = New IronPdf.ChromePdfRenderer()
Dim 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.

Häufig gestellte Fragen

Was sind Razor-Komponenten?

Razor-Komponenten sind ein UI-Framework in ASP.NET Core, das es Entwicklern ermöglicht, Webseiten mit einer Kombination aus C# und HTML zu erstellen, wobei die serverseitige Logik auch auf der Clientseite ausgeführt werden kann. Sie sind Teil des Blazor-Frameworks und unterstützen eine komponentenbasierte Architektur.

Wie verbessern Razor-Komponenten die Webentwicklung?

Razor-Komponenten vereinfachen die Webentwicklung, indem sie Entwickler in die Lage versetzen, C# und HTML zu verwenden, um dynamische und interaktive Webanwendungen zu erstellen, ohne auf JavaScript angewiesen zu sein. Dies führt zu einer nahtloseren Integration von serverseitiger Logik und clientseitiger Interaktivität.

Wie kann ich aus Razor-Komponenten ein PDF generieren?

Um PDFs aus Razor-Komponenten zu generieren, können Sie IronPDF verwenden, das die Umwandlung von HTML-Ausgaben der Komponenten in PDF-Format ermöglicht. Dies wird durch die Verwendung der IronPdf.ChromePdfRenderer-Klasse erreicht, um die Komponenten in eine PDF-Datei zu rendern.

Was sind die Vorteile der Verwendung von Razor-Komponenten?

Razor-Komponenten bieten mehrere Vorteile, darunter Wiederverwendbarkeit, Modularität, nahtlose Integration mit C#, serverseitige und clientseitige Ausführung, Echtzeitkommunikation mit SignalR und hohe Erweiterbarkeit.

Wie installiere ich IronPDF in meinem Projekt?

Um IronPDF zu Ihrem Projekt hinzuzufügen, verwenden Sie den NuGet-Paket-Manager in Visual Studio. Suchen Sie nach dem IronPDF-Paket und installieren Sie es, um PDF-Generierungsfunktionen in Ihren Razor-Komponenten zu ermöglichen.

Können Razor-Komponenten sowohl serverseitig als auch clientseitig ausgeführt werden?

Ja, Razor-Komponenten können sowohl serverseitig als auch clientseitig ausgeführt werden, je nach gewähltem Hosting-Modell. Diese Flexibilität ermöglicht es Entwicklern, die Anwendungsleistung und Sicherheit basierend auf den spezifischen Projektanforderungen zu optimieren.

Wie fördern Razor-Komponenten die Wiederverwendbarkeit?

Razor-Komponenten fördern die Wiederverwendbarkeit, indem sie eigenständig sind, was es ihnen ermöglicht, an mehreren Stellen innerhalb einer Anwendung oder in verschiedenen Projekten verwendet zu werden. Dies reduziert Code-Duplikation und verbessert Wartbarkeit und Skalierbarkeit.

Welche Anwendungsfälle gibt es für das Generieren von PDFs aus Web-Inhalten?

Das Generieren von PDFs aus Web-Inhalten mit IronPDF ist vorteilhaft für die Erstellung standardisierter Dokumente wie Berichte, Rechnungen und Dokumentationen, um sicherzustellen, dass der Inhalt sein Layout und Stil auf verschiedenen Plattformen behält.

Wie kann ich benutzerdefinierte UI-Elemente mit Razor-Komponenten erstellen?

Sie können benutzerdefinierte UI-Elemente erstellen, indem Sie sie in '.razor'-Dateien mit Razor-Syntax definieren. Dies ermöglicht es Entwicklern, C# und HTML zu kombinieren, um dynamische und wiederverwendbare Komponenten zu erstellen, die auf spezifische Anwendungsbedürfnisse zugeschnitten sind.

Wie funktionieren Parameter in Razor-Komponenten?

In Razor-Komponenten werden Parameter verwendet, um Daten von übergeordneten Komponenten an untergeordnete Komponenten zu übergeben. Dies wird durch das [Parameter]-Attribut ermöglicht, das die Kommunikation und den Datenaustausch zwischen verschiedenen Teilen einer Anwendung erleichtert.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen