Blazor Web Development Cookbook - Pawel Bazyluk - E-Book

Blazor Web Development Cookbook E-Book

Pawel Bazyluk

0,0
26,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

With support for both server-side and client-side hosting, as well as the flexibility to mix render modes, Blazor empowers you to leverage cloud computing while maintaining the performance of local applications. Paweł Bazyluk—a Blazor expert with over a decade of experience in .NET technologies—shows you how Blazor, a Microsoft framework, enables you to create interactive web applications using C# and .NET, while reducing reliance on JavaScript. This cookbook highlights Blazor’s vast possibilities using practical recipes that address key aspects of web development and showcase the framework's versatility in building modern, integrated applications.
Pawel demonstrates how to skillfully navigate component-based architecture, and create, parameterize, and customize components to achieve high modularity. Working through practical insights and hands-on guidance in each chapter, you’ll progress from advanced data binding and event handling intricacies to optimizing data display using grids. You’ll explore application state management, build interactive forms with validation, leverage Blazor’s routing engine, and keep every part of the application secure. The book also explores cutting-edge topics, touching on how to enhance your application with AI-powered features.
By the end of the book, you’ll be fully equipped to build robust, scalable, and secure web applications in Blazor.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 363

Veröffentlichungsjahr: 2024

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Blazor Web Development Cookbook

Tested recipes for advanced single-page application scenarios in .NET 9

Pawel Bazyluk

Blazor Web Development Cookbook

Copyright © 2024 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

The author acknowledges the use of cutting-edge AI, such as ChatGPT, with the sole aim of enhancing the language and clarity within the book, thereby ensuring a smooth reading experience for readers. It’s important to note that the content itself has been crafted by the author and edited by a professional publishing team.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Kaustubh Manglurkar

Publishing Product Manager: Chayan Majumdar

Book Project Manager: Sonam Pandey

Senior Editor: Rashi Dubey

Technical Editor: Simran Ali

Copy Editor: Safis Editing

Indexer: Manju Arasan

Production Designer: Shankar Kalbhor

Senior DevRel Marketing Executive: Nivedita Pandey

First published: November 2024

Production reference: 1071124

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK

ISBN 978-1-83546-078-8

www.packtpub.com

To everyone who supported me throughout the years. To my family - for always being my safe place. To my friends - for inspiring and challenging me. To my partner-in-crime - who always believes we can achieve more. I love you all. Thank you for being the pillars of my journey.

- Pawel Bazyluk

Contributors

About the author

Pawel Bazyluk is a seasoned Software Engineer with expertise in Blazor and .NET technologies. With a career spanning over a decade, Pawel has dedicated himself to mastering a diverse range of programming languages. In 2019, when Blazor started to surface, he realized its potential and has been positioning himself as a Blazor expert since. His innovative and user-centered approach to development has been key in solving numerous complex challenges for the companies he works with. Pawel’s journey in the tech industry is also marked by his enthusiasm for sharing knowledge and mentoring, making him a valued member of the developer community. His insights into Blazor and web development have gained recognition on LinkedIn and various tech forums.

I want to thank everyone who helped bring that book to reality. The Team at Packt - thank you for your guidance and for taking a chance on me. My technical reviewers - Wojtek, Christian, and Sebastian - thank you for your time and patience. The Team at Inspeerity - thank you for rooting for me and giving me space to focus on writing. And to my partner - thank you for making sure I don’t forget to eat and get enough sleep.

About the reviewers

Christian Stage is a dedicated IT professional and passionate Blazor developer. During his studies at the IT University of Copenhagen, he developed a keen interest in .NET, Python, machine learning, and physical computing.

Christian’s fascination with Blazor began as a Student Developer at Copenhagen Business School’s System Center Endpoint Team. He later became the Lead Developer at PreSeed Ventures (PSV), where he played a pivotal role in delivering a custom lead-generation tool using Blazor. Currently, as a Consultant at Netcompany, he is an active participant in the responsible digitalization of Denmark and has participated in the teaching of Blazor basics to new employees.

Sebastiaan Dammann is a seasoned web developer with over 12 years of experience. He began his career at a small sustainability agency, working with ASP.NET Web Forms and ASP Classic. For the past decade he has been working at the digital sustainability team at EY – the last number of years as lead developer. Since .NET 5 Sebastiaan has been developing enterprise applications using Blazor. Since the advent of .NET 5, he has been at the forefront of developing enterprise applications using Blazor. He is a language polygot, developing in Java, C#, C++, ASM, and TypeScript/Javascript.

Sebastiaan is passionate about 3D printing, writing on his personal blog, contributing to open source software, and raising his children Christina, Hannah and Isabella.

Wojciech Kasa is a seasoned software architect with nearly 20 years of professional experience. He specializes in distributed systems and Domain-Driven Design. Throughout his career he has held leadership roles, guiding teams in the design and implementation of high-performance, scalable systems.

He has a wonderful wife and two sons.

Aaron Piotrowski was trained as a 3D Artist and later converted to a full stack developer after finding that programming could take the conceptualization and imagery he created to fully functioning interactive applications. Having worked on everything from game animation, to custom frontend feature design and implementation for Fortune 500 and national brands, Angular web-app creation, and AR/VR projects on iOS, Android, HTC Vive and the Oculus Go, Aaron is a well rounded technology connoisseur. He can often be found in the office discussing Apple’s latest releases or debating the advantages of different technologies. Ultimately, he’s interested how innovative solutions can solve problems and create value for users.

Table of Contents

Preface

1

Working with Component-Based Architecture

Technical requirements

Initializing a project

Getting ready

How to do it...

How it works...

There’s more...

Creating your first basic component

Getting ready

How to do it...

How it works...

There’s more...

Declaring parameters on a component

Getting ready

How to do it...

How it works...

There’s more...

Detecting render mode at runtime

Getting ready

How to do it...

How it works...

Ensuring that a parameter is required

Getting ready

How to do it...

How it works...

Passing values from the parent component with CascadingParameter

Getting ready

How to do it...

How it works...

There’s more...

Creating components with customizable content

Getting ready

How to do it...

How it works...

There’s more...

Making components generic

Getting ready

How to do it...

How it works...

There’s more...

Decoupling components with DynamicComponent

Getting ready

How to do it...

How it works...

2

Synchronous and Asynchronous Data Binding

Technical requirements

Binding values with markup elements

Getting ready

How to do it…

How it works…

Binding to a specific DOM event

Getting ready

How to do it…

How it works…

There’s more…

Performing asynchronous actions after binding

Getting ready

How to do it…

How it works…

There’s more…

Customizing get and set binding logic

Getting ready

How to do it…

How it works…

There’s more…

Simplifying binding with the bind-Value pattern

Getting ready

How to do it…

How it works…

Binding with an external data provider

Getting ready

How to do it…

How it works…

3

Taking Control of Event Handling

Technical requirements

Hooking into event delegates

Getting ready

How to do it…

How it works…

There’s more…

Delegating with lambda expressions

Getting ready

How to do it…

How it works…

See also

Delegating with EventCallback

Getting ready

How to do it…

How it works…

There’s more…

Preventing default event actions

Getting ready

How to do it…

How it works…

There’s more…

Controlling event propagation

Getting ready

How to do it…

How it works…

There’s more…

Introducing custom events

Getting ready

How to do it…

How it works…

There’s more…

Handling long-running events

Getting ready

How to do it…

How it works…

There’s more…

4

Enhancing Data Display with Grids

Technical requirements

Refactoring a table to a grid component

Getting ready

How to do it…

How it works…

There’s more…

Attaching actions to parts of a grid

Getting ready

How to do it…

How it works…

There’s more…

Implementing pagination

Getting ready

How to do it…

How it works…

There’s more…

See also

Implementing sorting

Getting ready

How to do it…

How it works…

Implementing infinite scrolling

Getting ready

How to do it…

How it works…

There’s more…

Utilizing QuickGrid

Getting ready

How to do it…

How it works…

5

Managing Application State

Technical requirements

Having bookmarkable state

Getting ready

How to do it…

How it works…

There’s more…

Implementing an in-memory state container

Getting ready

How to do it…

How it works…

There’s more…

Injecting application state as a service

Getting ready

How to do it…

How it works…

See also

Invoking state changes from anywhere

Getting ready

How to do it…

How it works…

There’s more…

Persisting state

Getting ready

How to do it…

How it works…

There’s more…

Resolving persisted state

Getting ready

How to do it…

How it works…

There’s more…

Sharing state across interactive render mode boundaries

Getting ready

How to do it…

How it works…

There’s more…

6

Building Interactive Forms

Technical requirements

Binding a simple model to a form

Getting ready

How to do it…

How it works…

There’s more

Submitting static forms without full page reload

Getting ready

How to do it…

How it works…

There’s more…

Binding nested models to a form

Getting ready

How to do it…

How it works…

There’s more…

Utilizing built-in input components

Getting ready

How to do it…

How it works…

Handling file uploads with a form

Getting ready

How to do it…

How it works…

There’s more…

Securing a form with an anti-forgery token

Getting ready

How to do it…

How it works…

There’s more…

See also

7

Validating User Input Forms

Technical requirements

Adding validation to a form

Getting ready

How to do it…

How it works…

There’s more…

Leveraging data annotations for form validation

Getting ready

How to do it…

How it works…

There’s more…

Implementing custom validation attributes

Getting ready

How to do it…

How it works…

There’s more…

Validating complex data models

Getting ready

How to do it…

How it works…

There’s more…

Styling validation messages

Getting ready

How to do it…

How it works…

There’s more…

Displaying a toast when validation fails

Getting ready

How to do it…

How it works…

Enabling a submit option based on the form state

Getting ready

How to do it…

How it works…

There’s more…

8

Keeping the Application Secure

Technical requirements

Scaffolding identity

Getting ready

How to do it…

How it works…

There’s more…

Securing pages

Getting ready

How to do it…

How it works…

There’s more…

Securing markup areas

Getting ready

How to do it…

How it works…

There’s more…

Creating roles

Getting ready

How to do it…

How it works…

Modifying a user’s identity

Getting ready

How to do it…

How it works…

See also

Supporting roles’ and policies’ authorization

Getting ready

How to do it…

How it works…

There’s more…

Resolving authentication state in procedural logic

Getting ready

How it works…

9

Exploring Navigation and Routing

Technical requirements

Enabling routes from multiple assemblies

Getting ready

How to do it…

How it works…

Working with parameterized routes

Getting ready

How to do it…

How it works…

There’s more…

See also

Working with query parameters

Getting ready

How to do it…

How it works…

There’s more…

See also

Implementing unified deep linking

Getting ready

How to do it…

How it works…

There’s more…

Handling incorrect navigation requests

Getting ready

How to do it…

How it works…

See also

Executing an asynchronous operation with navigation

Getting ready

How to do it…

How it works…

See also

Canceling a long-running task when users navigate away

Getting ready

How to do it…

How it works…

Controlling navigation history

Getting ready

How to do it…

How it works…

10

Integrating with OpenAI

Technical requirements

Setting up an Azure OpenAI service

Getting ready

How to do it…

How it works…

There’s more…

See also

Implementing smart pasting

Getting ready

How to do it…

How it works…

There’s more…

Implementing a smart text area

Getting ready

How to do it…

How it works…

There’s more…

See also

Adding a ChatBot

Getting ready

How to do it…

How it works…

There’s more…

See also

Connecting an Azure OpenAI service to an existing data index

Getting ready

How to do it…

How it works…

There’s more…

See also

Index

Other Books You May Enjoy

Preface

Blazor is a powerful web framework introduced by Microsoft that allows developers to build interactive and modern web applications using C# and .NET instead of relying on JavaScript. Blazor bridges the gap between front-end and back-end development, offering a unified programming model that makes it easier to create full-featured web applications with a consistent and robust language stack. With Blazor, you can choose to host your application statically on the server; have a server-side interactivity through SignalR; build a client-side interface running directly in the browser, using WebAssembly; or mix all approaches however you see fit.

While you can easily find resources introducing Blazor basics and fundamental concepts, this book takes you deeper into advanced techniques and best practices for building enterprise-grade Blazor applications. The goal is to equip you with the tools to build robust, secure, scalable, and maintainable solutions. We will focus on practical, real-world examples and walk through the recipes you need to tackle the most common development challenges, leveraging the powerful features that Blazor offers.

The solutions and tricks in this cookbook come from or are inspired by two primary sources:

my years of experience developing Blazor applications across various industries, countries, and domainsBlazor community and insights from leading Blazor developers and experts

As Blazor continues to evolve, it is increasingly recognized as a game-changer in the .NET ecosystem, especially with the growing trend of full-stack C# development. As more companies adopt Blazor for their web development needs, the demand for skilled Blazor developers is rapidly increasing. This book will not only help you stay ahead of the curve but also ensure that you can confidently build and maintain Blazor applications that meet modern web standards.

I hope you find the book both insightful and practical. Your feedback is incredibly valuable to me, and I would be glad to hear about your experience. If you found the content helpful or if it made a difference in your projects, please consider leaving a review. Additionally, feel free to connect with me on LinkedIn or reach out via social media to share your thoughts, suggestions, or simply to discuss how the book has impacted your work. Your insights will help shape future editions and continue the conversation within the developer community.

Who this book is for

This book is intended for developers and software architects proficient in C# and .NET and already have experience in web development. Ideally, you must have a basic understanding of Blazor as we only skim through fundamentals to set the stage for the advanced topics.

The three main personas who will benefit from this content are:

web developers who want to leverage their C# and .NET skills to build modern, interactive web applications using Blazorsoftware architects looking to design and implement scalable, maintainable web applications using Blazor as part of their technology stackall Blazor enthusiasts who have a foundational understanding of Blazor and wish to deepen their knowledge by exploring advanced techniques, best practices, and real-world scenarios

What this book covers

Chapter 1, Working with Component-Based Architecture, introduces the architectural design of Blazor and explains the concept of a component. It also covers components parameterization, reusability and dynamic customization.

Chapter 2, Synchronous and Asynchronous Data Binding, is a comprehensive guide on advanced data binding techniques – application interactivity cornerstone. It explores two-way binding patterns and showcases practical case studies for asynchronous binding and input throttling, essential for efficient data exchange with external sources.

Chapter 3, Taking Control of Event Handling, covers everything there is to know about event handling in Blazor. It guides through working with event delegates, lambda expressions, capturing event arguments and leveraging Blazor-native EventCallback. It demonstrates techniques to control default event behaviors and propagation and building fully customized events. It also covers UX/UI tips for maintaining user awareness and interface responsiveness when handling long-running events.

Chapter 4, Enhancing Data Display with Grids, demonstrates how to enhance data representation with grids and attach actions to rows, columns, or individual cells. It also contains an example of infinite-scroll implementation and strategies for handling big datasets effectively with pagination and virtualization.

Chapter 5, Managing Application State, explores all corners of state management, from REST-like route patterns to support bookmarkable state, through in-memory and injectable state containers and to persisting state in the browser to prevent loss in higher latency scenarios. It also covers a practical implementation of globally injected state and components dynamically responding to the state changes.

Chapter 6, Building Interactive Forms, focuses on form handling by utilizing Blazor’s built-in components and the importance of securing forms, particularly in public-facing applications, by implementing antiforgery tokens and preventing cross-site request forgery attacks.

Chapter 7, Validating User Input Forms, showcases the form validation strategies. It covers implementing both in-memory and client-side validation for simple and complex object types and guides through integrating asynchronous server-side validation for robust data integrity. Moreover, it contains UI/UX tips, enabling conditional form submission based on validation states and enhancing user experience with toast notifications for validation messages.

Chapter 8, Keeping the Application Secure, highlights techniques for handling authentication and authorization, starting with JWT token support, through role-based authorization, and implementing custom policies for fine-grained control. It also covers creating a custom authentication provider to manage unique identity scenarios and building tenant-specific authorization logic.

Chapter 9, Exploring Navigation and Routing, guides through navigation and routing intricacies from supporting routes from external assemblies and securing routes with type constraints to centralizing the routing to enhance deep linking across the application. It’s also a practical guide to leveraging navigation events to cancel long-running requests to preserve memory and preventing accidental navigation to safeguard unsaved user inputs.

Chapter 10, Integrating with OpenAI, explores the integration of the Azure OpenAI service into a Blazor app and leveraging the possibilities of AI models. It showcases how to setup and manage the AI services and guides through creating a smart support ticket creator, leveraging smart pasting and smart input area. It also contains a walkthrough of adding an AI-powered chat bot to the application.

To get the most out of this book

You will need to have an understanding of the basics of Blazor, as well as fundamentals of web development. On top of that, you’re required to have an IDE that supports .NET and Blazor development as well as a browser that supports WebAssembly and modern CSS and HTML (which all modern web browsers do). You also need to have a .NET 9 SDK and runtime installed on your machine.

Software/Hardware covered in the book

OS Requirements

.NET 9

Windows, Mac OS X, and Linux (Any)

Blazor

Visual Studio, Visual Studio Code, Rider (Any)

Azure

If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Blazor-Web-Development-Cookbook. In case there’s an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “We intentionally designed Provider to match the ItemsProvider signature required by the Virtualize component, ensuring compatibility and seamless integration.”

A block of code is set as follows:

<div class="ticket">     <div class="name">Adult</div>     <div class="price">10.00 $</div> </div>

Any command-line input or output is written as follows:

dotnet new blazor -o BlazorCookbook.App -int Auto --framework net9.0

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: “Start Visual Studio and select Create a new project from the welcome window.”

Tips or important notes

Appear like this.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There’s more..., and See also).

To give clear instructions on how to complete a recipe, use these sections as follows:

Getting ready

This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There’s more…

This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Now you’ve finished Blazor Web Development Cookbook, we’d love to hear your thoughts! If you purchased the book from Amazon, please click here to go straight to the Amazon review page for this book and share your feedback or leave a review on the site that you purchased it from.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://download.packt.com/free-ebook/9781835460788

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

1

Working with Component-Based Architecture

Welcome to Blazor Web Development Cookbook. This book will be your comprehensive guide to enhancing your skills in building dynamic and scalable web applications with Blazor. It offers a collection of practical solutions and techniques for tackling the most common challenges in web development. In each chapter, we’ll dive into different areas of application development. This book is packed with detailed examples and actionable tips. We’ll explore a range of topics – from optimizing components, through managing application state to increasing your application’s interactivity and security. Having such a resource will allow you to gain development velocity and focus on addressing business requirements.

In this chapter, you’ll learn about the core principles of component-based architecture in Blazor. We’ll start by creating a basic component and progress to more complex aspects such as parameterization for reusability and handling required parameters. We’ll also explore advanced topics, such as building components with customizable content, implementing generic components, and increasing loose couplingwith DynamicComponent.

By the end of this chapter, you’ll be able to implement and optimize components in Blazor. Understanding component-based architecture is foundational in building more sophisticated, interactive, and responsive web applications. It’s also essential for writing scalable, maintainable, and reusable code.

We’re going to cover the following recipes in this chapter:

Initializing a projectCreating your first basic componentDeclaring parameters on a componentDetecting render mode at runtimeEnsuring that a parameter is requiredPassing values from the parent component with CascadingParameterCreating components with customizable contentMaking components genericDecoupling components with DynamicComponent

Technical requirements

You don’t need any paid tools or add-ons to kick off your Blazor journey. To aid with this, we’ve decided to limit the dependencies for the recipes in this book. You can pick up any topic independently whenever you need to.

For this chapter, you’ll need the following:

A modern IDE. We’ll be using Visual Studio 17.12.0, but any other is also fine, so long as it supports development in .NET 9.A modern web browser.The .NET 9 SDK. If it wasn’t part of your IDE installation, you can get it from https://dotnet.microsoft.com/en-us/download/dotnet/9.0.

You can find all the code examples for this chapter on GitHub at: https://github.com/PacktPublishing/Blazor-Web-Development-Cookbook/tree/main/BlazorCookbook.App.Client/Chapters/Chapter01.

Initializing a project

With .NET 9, the .NET team focused on improving the quality, stability, and performance of Blazor applications. Thankfully, there are no breaking changes between .NET 8, so you can safely raise the target framework of your application. However, with .NET 8, Blazor got a whole new solution type and rendering experience, so we’ll review the steps required to initialize a new project here.

Let’s initialize a Blazor Web App with a per-component rendering scope. It’s a strategic choice for our cookbook as it enables me to highlight various render mode caveats while we explore different areas of web development.

Getting ready

In this recipe, we’ll showcase initializing the project with the GUI provided as part of Visual Studio. So, start your IDE and dive in.

If you’re using the .NET CLI in your environment, I’ll provide equivalent commands in the There’s more... section.

How to do it...

Perform the following steps to initialize the Blazor Web App project:

Start Visual Studio and select Create a new project from the welcome window:

Figure 1.1: Navigating to the project creation panel

Use the search bar at the top of the next panel to narrow the list of available project types, select Blazor Web App, and confirm your choice by clicking Next:

Figure 1.2: Selecting Blazor Web App from the available project types

On the Configure your new project panel, define the project’s name and location and confirm these details by clicking Next:

Figure 1.3: Setting the name and location of the new project

On the Additional information panel, choose the following options:.NET 9.0 (Standard Term Support)under FrameworkAuto (Server and WebAssembly) under Interactive render modePer page/component under Interactivity location

On top of that, check the Include sample pages checkbox. Confirm your choice by clicking Create:

Figure 1.4: Configuring the project’s framework and interactivity

Here’s what your initial solution structure will look like:

Figure 1.5: Initial project structure

How it works...

In step 1, we started Visual Studio and selected the Create a new project option from the welcome menu. Since Visual Studio comes with many project templates preinstalled, in step 2, we utilized the search bar at the top of the panel and, by searching for the blazor keyword, we quickly found and selected Blazor Web App from the results list. We proceeded to the next stage by clicking the Next button. In step 3, we defined the project name and location. For this book, I chose BlazorCookbook.App and D:\packt. We continued the setup process by clicking Next.

In step 4, we configured the project. Considering that we’ll focus on Blazor in .NET 9, we chose .NET 9.0 (Standard Term Support) from the Framework dropdown. Then, we chose a render mode for our application from the Interactive render mode dropdown. With the None option, we effectively indicate that Blazor should use server-side rendering (SSR) mode. SSR is the fastest render mode as the markup is statically generated on the server but offers limited to no interactivity. When we expect interactivity, we must choose from the interactive modes. Here, Server (represented in the code as InteractiveServer) renders components on the server with UI interactions managed via a SignalR connection, allowing dynamic content updates while keeping component logic server-side. Alternatively, WebAssembly (InteractiveWebAssembly) renders components directly in the browser using WebAssembly, facilitating fully interactive experiences without server communication for UI updates. Lastly, with the Auto (Server and WebAssembly) option (InteractiveAuto), we let Blazor select the best rendering method based on the current environment state and network conditions. We want to explore various render mode behaviors, so Auto (Server and Webassembly) was the best option for us. For Interactivity location, we selected Per page/component so that we can define render modes at the component level, as opposed to Global, which would set the render mode globally across the project. We also checked the Include sample pages box to trigger the scaffold of a basic layout and CSS. We intentionally left Authentication type set to None to avoid unnecessary complexity, although we plan to revisit authentication in Chapter 8. We finalized the project creation process by clicking Create.

At this point, you should see the initial project structure. If you spot two projects, BlazorCookbook.App and BlazorCookbook.App.Client, that’s correct. Here, BlazorCookbook.App represents the server-side components of our application, while BlazorCookbook.App.Client is the client-side part that compiles into WebAssembly code. Everything that’s placed in BlazorCookbook.App.Client will be transmitted to the user’s browser, so you shouldn’t place any sensitive or confidential information there. Since BlazorCookbook.App references BlazorCookbook.App.Client, there’s no need to duplicate code, regardless of how it’s rendered initially.

There’s more...

If your IDE doesn’t have a GUI similar to Visual Studio, you can leverage the cross-platform .NET CLI. Navigate to your working directory and run the following command to initialize a Blazor Web App project with the same configuration that was outlined in step 4:

dotnet new blazor -o BlazorCookbook.App -int Auto --framework net9.0

Creating your first basic component

A component is a self-contained chunk of the user interface (UI). A component in Blazor is a .NET class with markup, created as a Razor (.razor) file. In Blazor, components are the primary building blocks of any application and encapsulate markup, logic, and styling. They enable code reusability and increase code maintainability and testability. This modular approach streamlines the development process greatly.

For our first component, we’ll create a Ticket component that renders a tariff name and a price when the user navigates to a page.

Getting ready

Before you dive into creating the first component, in your Blazor project, create a Recipe02 directory – this will be your working directory.

How to do it...

Follow these steps to create your first component:

Navigate to the Recipe02 directory that you just created.Use the Add New Item feature and create a Razor component:

Figure 1.6: Adding a new Razor component prompt

In the Ticket component, add supporting HTML markup: <div class="ticket">     <div class="name">Adult</div>     <div class="price">10.00 $</div> </div>Add a new Offer component. Use the @page directive to make it navigable and render the Ticketcomponent within: @page "/ch01r02" <Ticket />

How it works...

In step 1, we navigated to Recipe02 – our working directory. In step 2, we leveraged a built-in Visual Studio prompt to create files and create the first component: Ticket. While building components in the Razor markup syntax, we named our component file Ticket.razor. In step 3, we added simple markup to Ticket – we rendered Adult and 10.00 $, which describe a given ticket. In step 4, we created our first page – the Offer page. In Blazor, any component can become a page with the help of a @page directive, which requires a fixed path argument starting with /. The @page "/ch01r02" directive enables navigation to that component. In the Offer markup, we embedded Ticket using the self-closing tag syntax – a simpler, more convenient equivalent of the explicit opening and closing tags (<Ticket></Ticket>). However, we can only utilize it when the component doesn’t require any additional content to render.

There’s more...

While componentization in Blazor offers numerous benefits, it’s essential to know when and how much to use it. Components are a great way to reuse representation markup with various data objects. They significantly enhance code readability and testability. However, caution is necessary – you can overdo componentization. Using too many components leads to increased reflection overhead and unnecessary complexities in managing render modes. It’s especially easy to overlook when you’re refactoring grids or forms. Ask yourself whether every cell must be a component and whether you need that input encapsulated. Always weigh what you might gain from higher markup granularity with the performance cost it brings.

Declaring parameters on a component

In Blazor, component parameters allow you to pass data into components. It’s the first step in making your application dynamic. Component parameters are like method parameters in traditional programming. You can utilize the same primitive, as well as the reference and complex types. This results in code flexibility, simplified UI structures, and high markup reusability.

Let’s create a parametrized component that represents a ticket so that we can display any incoming tariff and price without unnecessary code duplication or markup incoherence.

Getting ready

Before you dive into component parameterization, do the following:

Create a Recipe03 directory – this will be your working directoryCopy the Ticket component from the Creating your first basic component recipe or copy its implementation from the Chapter01/Recipe02 directory of this book’s GitHub repository

How to do it...

To declare parameters on your component, start with these foundational steps:

In the Ticket component, declare parameters in the @code block: @code {     [Parameter] public string Tariff { get; set; }     [Parameter] public decimal Price { get; set; }     [Parameter]     public EventCallback OnAdded { get; set; } }Modify the Ticket markup so that you can render values from parameters: <div class="ticket">     <div class="name">@Tariff</div>     <div class="price">         @(Price.ToString("0.00 $"))     </div>     <div class="ticket-actions">         <button @onclick="@OnAdded">             Add to cart         </button>     </div> </div>Create an Offer page and enhance it so that it renders in InteractiveWebAssembly mode: @page "/ch01r03" @rendermode InteractiveWebAssemblyBelow the functional directives in the Offer component, add two parametrized instances of Ticket. Implement an Add() method as a placeholder for interactivity: <Ticket Tariff="Adult" Price="10.00m"         OnAdded="@Add" /> <Ticket Tariff="Child" Price="5.00m"         OnAdded="@Add" /> @code {     private void Add()         => Console.WriteLine("Added to cart!"); }

How it works...

In step 1, we extended the Ticket component with a @code block, which Blazor recognizes as a container for the C# code. Within this @code block, we used the Parameter attribute to mark properties that are settable externally, such as method arguments in C#. In our example, we used a string for a ticket tariff and a decimal for its price. For the last parameter, we used the EventCallback type. It’s a Blazor-specific struct that carries an invokable action with an additional benefit. When you change the UI state, you should use the StateHasChanged() life cycle method to notify Blazor that something happened. By design, EventCallback triggers StateHasChanged() automatically, so you can’t omit it accidentally. In step 2, we rebuilt the Ticket markup based on parameter values that we accessed using the @ symbol. That symbol signaled to the compiler that we were switching to dynamic C# code. If you pair it with round brackets, you can embed complex code blocks as well, as we did when we formatted the price in a money format.

In step 3, we created a navigable Offer page. This time, on top of the @page directive, we also declared a @rendermode directive, which allowed us to control how our component renders initially. We can choose from any of the render modes that a Blazor Web App supports, but as we expect some interactivity on the page, we opted for InteractiveWebAssembly mode. In step 4, in the @code block of Offer, we implemented an Add() placeholder method that simulates adding a ticket to the cart. We also implemented the Offer markup, where we rendered two Ticket instances with different parameters. You pass parameter values similarly to standard HTML attributes such as class or style. Blazor automatically recognizes that you’re calling a component, not an HTML element. Finally, we rendered Adult and Child tickets and attached the Add() method to the exposed EventCallback parameter.

There’s more...

You must be aware that the number of parameters can directly affect the rendering speed. That’s because the renderer uses reflection to resolve parameter values. Over-reliance on reflection can significantly hinder performance. You can optimize that process by overriding the SetParametersAsync() method of the component life cycle, though that’s an advanced operation. Instead, you should focus on keeping the parameters list concise or introducing wrapper classes where necessary.

Earlier in this chapter, we declared a specific render mode for a component when your Blazor application is set to expect interactivity at the page or component level. However, when you enable interactivity globally, you can still exclude certain pages from interactive routing. You’ll find it useful for pages that depend on standard request/response cycles or reading or writing HTTP cookies:

@attribute [ExcludeFromInteractiveRouting]

To enforce static server-side rendering on a page, you must add the ExcludeFromInteractiveRouting attribute, using the @attribute directive, at the top of the page. In this case, you no longer add the @rendermode directive as it’s dedicated to declaring interactive render modes.

Detecting render mode at runtime

Understanding where and how your component renders is crucial for optimizing performance and tailoring user experience. Blazor allows you to detect the render location, interactivity, and assigned render mode at runtime. You can query whether the component is operating in an interactive state or just prerendering. These insights open up new possibilities for debugging, performance optimization, and building components that adapt dynamically to their rendering context.

Let’s hide the area with tickets in the Offer component to prevent user interactions, such as adding tickets to the cart, until the component is ready and interactive.

Getting ready

Before you explore render mode detection, do the following:

Create a Recipe04 directory – this will be your working directoryCopy the Offer and Ticket components from the Declaring parameters on a component recipe or copy their implementations from the Chapter01/Recipe03 directory of this book’s GitHub repository

How to do it...

Follow these steps:

Navigate to the Offer component and update the path attached to the @page directive to avoid routing conflicts: @page "/ch01r04" @rendermode InteractiveWebAssemblyBelow the component directives, add some conditional markup to indicate that the component is getting ready based on the value of the RendererInfo.IsInteractive property: @if (!RendererInfo.IsInteractive) {     <p>Getting ready...</p>     return; } @* existing markup is obscured, but still down here *@

How it works...

In step 1, we navigated to the Offer component and updated the path that was assigned to the @page directive. Blazor doesn’t allow duplicated routes, so we triggered a conflict since we copied the Offer component with a route from the Declaring parameters on a component recipe.

In step 2, we introduced a conditional markup block below the component directives. We leveraged the RendererInfo property that the ComponentBase class exposes, allowing us to track the component rendering state. The RendererInfo property has two properties:

The RendererInfo.Name property tells us where the component is currently running and returns the following options:Static: This indicates that the component is running on the server without any interactivityServer: This indicates that the component is running on the server and will be interactive after it fully loadsWebAssembly: This indicates that the component is running in the client’s browser and becomes interactive after loadingWebView: This indicates that it’s dedicated to .NET MAUI and native devicesThe RendererInfo.IsInteractive property shows whether the component is in an interactive state or not (such as during prerendering or static SSR)

We leveraged the RendererInfo.IsInteractive property to detect whether the interactivity is ready. If it isn’t, we display a Getting ready... message to inform users they should wait.

Ensuring that a parameter is required

The EditorRequired attribute indicates to your IDE that passing data to the component is functionally critical. This attribute triggers data validation at compile time, creating a quick feedback loop and enhancing code quality. Utilizing the EditorRequired attribute ensures neither you nor anyone from your team will fall into errors due to missing parameters. You can simplify your code by skipping initial parameter value validation. Using the EditorRequired attribute leads to robust and predictable component behavior throughout the application.

Let’s enhance the Ticket component parameters so that Blazor treats them as required. You’ll also learn how to configure your IDE so that you can flag any missing required parameters as compilation errors.

Getting ready

Before setting up the required parameters, do the following:

Create a Recipe05 directory – this will be your working directoryCopy the Ticket and Offer components from the previous recipe or copy their implementation from the Chapter01/Recipe04 directory of this book’s GitHub repository

How to do it...

Ensure parameters are required in your component by following these steps:

Navigate to the @code block of the Ticket component and extend attribute collection on parameters with the EditorRequired attribute: @code {     [Parameter, EditorRequired]     public string Tariff { get; set; }     [Parameter, EditorRequired]     public decimal Price { get; set; }     [Parameter]     public EventCallback OnAdded { get; set; } }Now, navigate to the .csproj file of the project where you’re keeping your components.Add the RZ2012 code to the WarningsAsErrors section: <Project Sdk="Microsoft.NET.Sdk.Web">   <PropertyGroup>     <TargetFramework>net9.0</TargetFramework>     <ImplicitUsings>enable</ImplicitUsings>     <WarningsAsErrors>RZ2012</WarningsAsErrors>   </PropertyGroup>   <!-- ... --> </Project>In the Offer markup, modify the Ticket instances by removing the OnAdded parameter from both. Additionally, remove the Price parameter from the second instance: <Ticket Tariff="Adult" Price="10.00m" /> <Ticket Tariff="Child" />Compile your application so that you can see your IDE flagging the omitted but required Price parameter:

Figure 1.7: IDE flags missing the Price parameter as a compilation error

How it works...

In step 1, we enhanced the Tariff and Price parameters of the Ticket component with the EditorRequired attribute. This prompts your IDE to expect these values during compilation and flag the missing ones as warnings by default. I suggest that you raise that severity. In step 2, you navigated to the .csproj file of your project. Here, as outlined in step 3, you either found or added the WarningsAsErrors section and included the RZ2012 code within. In step 4, we broke the Offer markup a little. We removed the OnAdded parameter from both Ticket instances and the Price parameter from one of them. Now, any compilation attempt will end with an error, similar to the one shown in step 5. This makes it practically impossible to miss required assignments and encounter related rendering errors. Notice that as we didn’t mark the OnAdded parameter with the EditorRequired attribute, the compiler will treat it as optional and allow it to be skipped.

Passing values from the parent component with CascadingParameter

Sharing parameters across multiple components is a common scenario in web applications. It boosts performance as data can be shared rather than being requested from an external source by each component. It also simplifies the code, especially in parent-child scenarios. In Blazor, that’s where the concept of CascadingParameter comes into play. Its counterpart, CascadingValue