Blazor Web Development Cookbook: Tested recipes for advanced single-page application scenarios in .NET 9
()
Related to Blazor Web Development Cookbook
Related ebooks
Web Development with Blazor: A practical guide to building interactive UIs with C# 12 and .NET 8 Rating: 0 out of 5 stars0 ratingsBuilding Web Applications with Blazor and C# Rating: 0 out of 5 stars0 ratingsBuilding a Web App with Blazor and ASP .Net Core: Create a Single Page App with Blazor Server and Entity Framework Core Rating: 0 out of 5 stars0 ratingsBlazor Web Application Development: Definitive Reference for Developers and Engineers Rating: 0 out of 5 stars0 ratings.NET MAUI Cookbook: Build a full-featured app swiftly with MVVM, CRUD, AI, authentication, real-time updates, and more Rating: 0 out of 5 stars0 ratingsHallo Blazor: Building Modern Full-Stack Web Apps with .NET 9.0 Rating: 0 out of 5 stars0 ratingsArchitecting ASP.NET Core Applications: An atypical design patterns guide for .NET 8, C# 12, and beyond Rating: 0 out of 5 stars0 ratingsReact and React Native: Build cross-platform JavaScript and TypeScript apps for the web, desktop, and mobile Rating: 0 out of 5 stars0 ratingsModern Full-Stack React Projects: Build, maintain, and deploy modern web apps using MongoDB, Express, React, and Node.js Rating: 0 out of 5 stars0 ratingsTools and Skills for .NET 8: Get the career you want with good practices and patterns to design, debug, and test your solutions Rating: 0 out of 5 stars0 ratingsJump Start Web Performance Rating: 0 out of 5 stars0 ratingsJavaScript Design Patterns: Deliver fast and efficient production-grade JavaScript applications at scale Rating: 0 out of 5 stars0 ratingsFull-Stack Web Development with TypeScript 5: Craft modern full-stack projects with Bun, PostgreSQL, Svelte, TypeScript, and OpenAI Rating: 0 out of 5 stars0 ratingsReact Anti-Patterns: Build efficient and maintainable React applications with test-driven development and refactoring Rating: 0 out of 5 stars0 ratingsAngular Design Patterns and Best Practices: Create scalable and adaptable applications that grow to meet evolving user needs Rating: 0 out of 5 stars0 ratingsReact Key Concepts: An in-depth guide to React's core features Rating: 0 out of 5 stars0 ratingsMinimal APIs in ASP.NET 9: Design, implement, and optimize robust APIs in C# with .NET 9 Rating: 0 out of 5 stars0 ratingsMastering the Dot NET Core Interview: Dot Net Interview Preparation, #4 Rating: 0 out of 5 stars0 ratingsFrontend Software Development and Best Practices: A Concise Guide Rating: 5 out of 5 stars5/5SignalR Blueprints Rating: 0 out of 5 stars0 ratings
Programming For You
Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Beginning Programming with Python For Dummies Rating: 3 out of 5 stars3/5Microsoft Azure For Dummies Rating: 0 out of 5 stars0 ratingsPython Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5PYTHON PROGRAMMING Rating: 4 out of 5 stars4/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Python for Data Science For Dummies Rating: 0 out of 5 stars0 ratingsAlgorithms For Dummies Rating: 4 out of 5 stars4/5Beginning Programming with C++ For Dummies Rating: 4 out of 5 stars4/5The Recursive Book of Recursion: Ace the Coding Interview with Python and JavaScript Rating: 0 out of 5 stars0 ratingsPYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Problem Solving in C and Python: Programming Exercises and Solutions, Part 1 Rating: 5 out of 5 stars5/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratings
Reviews for Blazor Web Development Cookbook
0 ratings0 reviews
Book preview
Blazor Web Development Cookbook - 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 domains
Blazor 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 Blazor
software architects looking to design and implement scalable, maintainable web applications using Blazor as part of their technology stack
all 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.
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:
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