.NET HELP

Blazor .NET 8 (Developer Tutorial)

Published December 24, 2023
Share:

Blazor, the full-stack web UI framework, has evolved significantly with the release of .NET 8.0. This update brings forth various features and enhancements that empower developers to build interactive and modern web applications using C# and .NET.

In this article, we'll delve into the key aspects of Blazor .NET 8.0, exploring the new rendering modes, project templates, tooling improvements, and more.

Blazor .NET 8 (Developer Tutorial): Figure 1

Understanding Blazor Render Modes

Blazor in .NET 8.0 introduces three render modes:

  1. Static server rendering: Generates static HTML for optimal performance.
  2. Interactive Server rendering: Utilizes the server-side ASP.NET Core runtime for initial rendering and interactivity.
  3. Interactive WebAssembly rendering: Leverages the .NET WebAssembly runtime on the client for subsequent rendering and interactivity.

The Versatile Interactive Auto Rendering

One of the highlights is the Interactive Auto rendering mode, which combines server-side rendering for content with subsequent rendering and interactivity on the client using the .NET WebAssembly runtime. This results in a faster app startup experience, making it an attractive option for developers.

Introduction of the Blazor Web App Template

.NET 8.0 introduces the Blazor Web App template, a unified starting point that combines the strengths of Blazor Server and Blazor WebAssembly hosting models.

This template incorporates new features like static server rendering, streaming rendering, enhanced navigation, and form handling. The consolidation of project templates simplifies the development process.

Streamlined JS Initializers for Blazor Web Apps

The traditional JS initializers have been replaced with a new set for Blazor Web Apps, offering better control over tasks such as customizing the loading process, logging levels, and other options. This change enhances the development experience and aligns with the goal of unifying hosting models in .NET 8.0.

Splitting Prerendering and Integration Guidance

To provide more focused coverage, the guidance on prerendering and integration has been split into separate articles. This change aims to simplify understanding and implementation, making it easier for developers to follow best practices.

Effortless State Persistence in Blazor Web Apps

Blazor Web Apps now automatically persist any registered app-level state created during prerendering. This eliminates the need for the Persist Component State Tag Helper, streamlining the persisting and reading component state process.

Enhanced Form Handling and Model Binding

.NET 8.0 brings improved form-handling capabilities to Blazor components, including model binding and data validation. The framework honors data contract attributes, providing developers with more control over how form data is bound to the model. The introduction of anti-forgery support adds an extra layer of security to form submissions.

Enhanced Navigation and Form Handling

Static server rendering in Blazor .NET 8.0 introduces a significant improvement in page navigation and form handling. Traditionally, full-page refreshes occurred when navigating or submitting a form.

With the enhanced navigation feature, Blazor intercepts the request and performs a fetch request, patching the rendered response content seamlessly into the browser DOM. This avoids full page refreshes, resulting in faster and smoother page loads while preserving more of the page state.

Enhanced navigation is enabled by default when the Blazor script (blazor.web.js) is loaded, and it can be optionally enabled for specific forms. The new enhanced navigation API allows developers to refresh the current page programmatically, providing even more control over the user experience.

Streaming Rendering

Blazor .NET 8.0 introduces streaming rendering, a powerful feature that enhances the user experience for pages executing long-running asynchronous tasks. With streaming rendering, pages can render placeholder content while asynchronous operations are in progress.

Once complete, the updated content is streamed to the client on the same response connection and seamlessly patched into the DOM. This approach ensures that the main layout of the app renders quickly, and the page updates as soon as the content becomes available.

Keyed Services Injection

Blazor now supports injecting keyed services using the Inject attribute. Keys enable the scoping of service registration and consumption in dependency injection scenarios.

The new InjectAttribute.Key property allows developers to specify the key for the service to inject, opening up new possibilities for service scoping.

Accessing HttpContext as a Cascading Parameter

Blazor .NET 8.0 introduces the ability to access the current HttpContext as a cascading parameter from a static server component. This enhancement is particularly useful for inspecting and modifying headers or other properties related to the HTTP context.

Rendering Razor Components Outside of ASP.NET Core

Blazor .NET 8.0 opens up the possibility of rendering Razor components outside the context of an HTTP request. This flexibility allows developers to render Razor components directly to a string or stream independently of the ASP.NET Core hosting environment.

This feature is especially handy for scenarios where generating HTML fragments, such as emails or static site content, is necessary.

Sections Support

In Blazor .NET 8.0, the introduction of SectionOutlet and SectionContent components revolutionizes content management. These components allow developers to define placeholders in layouts, later filled in by specific pages.

Sections can be referenced using unique names or object IDs, providing flexibility and reusability in constructing dynamic web layouts.

Error Page Support

Blazor Web Apps in .NET 8.0 now boast robust error page support, allowing developers to define custom error pages for use with the ASP.NET Core exception handling middleware.

The default error page (Components/Pages/Error.razor) provides a consistent user experience. Even when interactivity is enabled, the error page renders as a static server component, ensuring stability during exception scenarios.

QuickGrid From Experimental to Essential

QuickGrid, the high-performance grid component, has graduated from experimental status to become an integral part of the Blazor framework in .NET 8.

This component simplifies the display of tabular data while offering powerful features like sorting, filtering, paging, and virtualization. Learn more about QuickGrid in the ASP.NET Core Blazor QuickGrid documentation.

Route to Named Elements

Blazor .NET 8.0 introduces support for client-side routing to navigate directly to specific HTML elements on a page using standard URL fragments. By specifying an identifier for an HTML element with the standard id attribute, Blazor seamlessly scrolls to that element when the URL fragment matches the element identifier.

Root-Level Cascading Values

Blazor .NET 8.0 enhances cascading values by introducing root-level cascading values that can be registered for the entire component hierarchy. Named cascading values and subscriptions for update notifications are now supported, providing greater flexibility and control.

Virtualize Empty Content

The new EmptyContent parameter on the Virtualize component enables developers to supply content when the component has loaded and either item is empty or ItemsProviderResult<T>.TotalItemCount is zero.

This empowers developers to create more intuitive and user-friendly interfaces.

Circuit Management and SignalR Monitoring

Blazor .NET 8.0 introduces the ability to close circuits when there are no remaining interactive server components. This optimization frees up server resources and enhances overall performance.

Additionally, developers can now monitor inbound circuit activity in server-side apps using the CreateInboundActivityHandler method on CircuitHandler.

Faster Runtime Performance with the Jiterpreter

The Jiterpreter, a new runtime feature in .NET 8, introduces partial Just-in-Time (JIT) compilation support when running on WebAssembly. This results in improved runtime performance, offering a smoother experience for users interacting with Blazor WebAssembly applications.

Ahead-of-Time (AOT) SIMD and Exception Handling

Blazor WebAssembly's AOT compilation now defaults to using WebAssembly Fixed-width SIMD and WebAssembly Exception handling. This strategic choice significantly enhances runtime performance, providing a more efficient and responsive user experience.

Webcil Packaging for Web-Friendly Deployment

Blazor WebAssembly now utilizes Webcil, a web-friendly packaging of .NET assemblies. This ensures compatibility in environments that block the download or use of .dll files, addressing deployment challenges. Webcil is enabled by default for Blazor WebAssembly apps.

Blazor WebAssembly Debugging Improvements

Debugging Blazor WebAssembly apps has become more streamlined in .NET 8. The debugger now downloads symbol data from configured locations in Visual Studio preferences, enhancing the debugging experience for apps utilizing NuGet packages.

Additionally, debugging is now supported in Firefox, requiring configuration for remote debugging and connecting through the .NET WebAssembly debugging proxy.

Content Security Policy (CSP) Compatibility

Blazor WebAssembly in .NET 8.0 eliminates the need to enable the unsafe-eval script source when specifying a Content Security Policy (CSP). This enhancement simplifies security configurations, making it easier to enforce a robust CSP for Blazor WebAssembly applications.

Handling Exceptions Outside of Component Lifecycle

The introduction of ComponentBase.DispatchExceptionAsync allows developers to process exceptions thrown outside a Razor component's lifecycle call stack.

This feature permits the component's code to treat exceptions as though they're lifecycle method exceptions, ensuring a more consistent and controlled error-handling mechanism.

Introducing Iron Suite

Iron Suite by Iron Software, developed by Iron Software, consists of several useful libraries, enabling developers to build powerful Blazor apps. It provides solutions for adding PDF functionality, Excel or CSV file functionality, image-to-text recognition, barcode & QR code generation and reading, and the ability to zip or extract files.

Iron Suite is the perfect choice to consider for web development using the Blazor WebAssembly hosting model, or any Microsoft technologies, including the Blazor WebAssembly app, Blazor server app, ASP.NET Core MVC APP, ASP.NET core WEB APIs, or any application built in .NET runtime, be it any version.

Libraries of Iron Suite

  1. IronPDF for creating, manipulating, and extracting data from PDF files seamlessly.

    The standout function of IronPDF is converting HTML to PDF, with full layout and style preservation. It’s perfect for generating PDFs from web content, including reports, invoices, and documentation. You can convert HTML files, URLs, or HTML strings 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
    VB   C#
  2. IronOCR (Optical Character Recognition) for extracting text from scanned images or PDFs, enhancing data accessibility.
  3. IronXL for reading, writing, and manipulating Excel spreadsheets with efficiency.
  4. IronBarcode for generating and reading barcodes in various formats, facilitating data encoding and retrieval.
  5. IronQR for creating and reading QR codes using Machine Learning
  6. IronWebScraper for extracting valuable data from websites, enhancing the capabilities of web-based applications.
  7. IronZIP for compressing and decompressing files, streamlining data storage and transfer processes.

Blazor .NET 8 (Developer Tutorial): Figure 2

What Sets Iron Suite Apart

  1. Gain access to the entire suite at the price of just two individual products, maximizing the value of your investment.
  2. Whether you're working on Windows, macOS, or Linux, Iron Suite ensures compatibility across (almost) all platforms.
  3. Experience a swift journey from download to production, with the ability to be up and running in as little as 5 minutes.
  4. Access detailed documentation and examples for all features, providing clarity and guidance throughout the development process.
  5. A dedicated team of engineers is available 24/5 to assist you with any queries, ensuring a smooth development experience.
  6. Iron Suite comes with a 30-day, no-questions-asked refund policy, providing confidence and peace of mind.

Conclusion

In conclusion, the release of Blazor .NET 8.0 marks a significant milestone in the evolution of full-stack web UI development with C# and .NET.

The introduction of new rendering modes, the Blazor Web App template, enhanced navigation, and a myriad of other features make it a compelling choice for developers aiming to create modern and interactive web applications.

Blazor .NET 8.0 also introduces compelling features such as enhanced form handling, streaming rendering, and the ability to inject keyed services, adding depth and flexibility to development.

The introduction of Iron Suite by Iron Software complements Blazor's capabilities, offering a comprehensive toolkit for document-related tasks within the .NET ecosystem.

Blazor .NET 8.0 empowers developers to create robust and feature-rich web applications by utilizing Iron Suite.

The combination of powerful features, improved performance, and the support of a vibrant developer community positions Blazor as a compelling choice for modern web development.

< PREVIOUS
C# KeyValuePair (How it Works For Developers)
NEXT >
BinaryKits.Zpl.Viewer (How it Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,781,565 View Licenses >