31,19 €
Blazor WebAssembly makes it possible to run C# code on the browser instead of having to use JavaScript, and does not rely on plugins or add-ons. The only technical requirement for using Blazor WebAssembly is a browser that supports WebAssembly, which, as of today, all modern browsers do. Blazor WebAssembly by Example is a project-based guide for learning how to build single-page web applications using the Blazor WebAssembly framework. This book emphasizes the practical over the theoretical by providing detailed step-by-step instructions for each project.
You'll start by building simple standalone web applications and progress to developing more advanced hosted web applications with SQL Server backends. Each project covers a different aspect of the Blazor WebAssembly ecosystem, such as Razor components, JavaScript interop, event handling, application state, and dependency injection. The book is designed in such a way that you can complete the projects in any order.
By the end of this book, you will have experience building a wide variety of single-page web applications with .NET, Blazor WebAssembly, and C#.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 219
Veröffentlichungsjahr: 2021
A project-based guide to building web apps with .NET, Blazor WebAssembly, and C#
Toi B. Wright
BIRMINGHAM—MUMBAI
Copyright © 2021 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.
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.
Associate Group Product Manager: Pavan Ramchandani
Senior Editor: Keagan Carneiro
Content Development Editor: Adrija Mitra
Technical Editor: Saurabh Kadave
Copy Editor: Safis Editing
Project Coordinator: Manthan Patel
Proofreader: Safis Editing
Indexer: Tejal Daruwale Soni
Production Designer: Vijay Kamble
First published: June 2021
Production reference: 1040621
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80056-751-1
www.packt.com
To my boys, for their never-ending patience and understanding. To my readers, for their ceaseless curiosity about new technologies.
– Toi B. Wright
Hi, friends! I've known Toi Wright for more than 15 years. I first met her at the Microsoft MVP Summit in Redmond back in 2005, if you can believe that. She's a brilliant technologist, community leader, and tech organizer, and we see each other every year at the annual Microsoft MVP Summit. I've had the opportunity to travel from my home in Portland to beautiful Dallas to speak to her in person at the Dallas ASP.NET User Group, of which she's the founder and organizer.
Toi has been very active in the ASP.NET community for many years. She has written courseware for Microsoft on ASP.NET and this is her second book on the topic. She's a respected programmer, architect, and communicator.
In this book, she walks you step by step through the creation of a number of standalone projects that are built on the Blazor WebAssembly framework. You'll learn how to leverage your experience with the .NET ecosystem to complete many different types of projects. Blazor takes .NET and your .NET skills to the web in a new way, and this book is the key to enabling that.
In Blazor WebAssembly by Example, Toi has shared her extensive knowledge and years of experience as a web developer and created an easy-to-follow guide for you to quickly learn how to use the Blazor WebAssembly framework. Through her words, step-by-step instructions, copious screenshots, and code samples, you will get started with running C# in your browser instead of JavaScript. Everything she'll show you, including .NET and Blazor itself, is all open source and based on open standards! I'm so glad that we both have a partner in Toi Wright to guide us in this powerful new web framework!
Scott Hanselman – hanselman.com
Partner Program Manager at Microsoft
Toi B. Wright has been obsessed with ASP.NET for almost 20 years. She is the founder and president of the Dallas ASP.NET User Group. She has been a Microsoft MVP in ASP.NET for 16 years and is also an ASPInsider. She is an experienced full-stack software developer, book author, courseware author, speaker, and community leader with over 25 years of experience. She has a B.S. in computer science and engineering from the Massachusetts Institute of Technology (MIT) and an MBA from Carnegie Mellon University (CMU).
You can find her on Twitter at @misstoi.
I would like to thank my husband and my two sons for their continued support, patience, and encouragement throughout the protracted process of writing this book.
Jürgen Gutsch is a .NET-addicted web developer. He has been working with .NET and ASP.NET since the early versions in 2002. Before that, he wrote server-side web applications using classic ASP. He is also an active person in the .NET developer community. Jürgen writes for the dotnetPro Magazine, one of the most popular German-speaking developer magazines. He also publishes articles in English on his blog, ASP.NET Hacker, and contributes to several open source projects. Jürgen has been a Microsoft MVP since 2015.
The best way to contact him is using Twitter: @sharpcms.
He works as a developer, consultant, and trainer for the digital agency YOO Inc., located in Basel, Switzerland. YOO Inc. serves national as well as international clients and specializes in creating custom digital solutions for distinct business needs.
Blazor WebAssembly is a framework, built on the popular and robust ASP.NET framework, that allows you to build single-page web applications that use C# on the client instead of JavaScript. Blazor WebAssembly does not rely on plugins or add-ons. It only requires that the browser support WebAssembly – and all modern browsers support it.
In this book, you will complete practical projects that will teach you the fundamentals of the Blazor WebAssembly framework. Each chapter includes a standalone project with detailed step-by-step instructions. Each project is designed to highlight one or more important concepts concerning Blazor WebAssembly. By the end of the book, you will have experience with building both simple standalone web applications and hosted web applications with SQL Server backends.
This book is for experienced web developers who are tired of constantly learning the latest new JavaScript framework and want to leverage their experience with .NET and C# to build web applications that can run anywhere.
This book is for anyone who wants to learn Blazor WebAssembly quickly by emphasizing the practical over the theoretical. It uses complete, step-by-step sample projects that are easy to follow to teach you the concepts required to develop web apps using the Blazor WebAssembly framework.
You do not need to be a professional developer to benefit from the projects in this book, but you do need some experience with C# and HTML.
Chapter 1, Introduction to Blazor WebAssembly, provides an introduction to the Blazor WebAssembly framework. It explains the benefits of using the Blazor framework and describes the differences between the two hosting models: Blazor Server and Blazor WebAssembly. After highlighting the advantages of using the Blazor WebAssembly framework, the goals and support options for WebAssembly are discussed. Finally, it guides you through the process of setting up your computer to complete the projects in this book. By the end of this chapter, you will be able to proceed to any of the other chapters in this book.
Chapter 2, Building Your First Blazor WebAssembly Application, provides an introduction to Razor components through the creation of a simple project. This chapter is divided into three sections. The first section explains Razor components, routing, and Razor syntax. The second section walks you step by step through the process of creating your first Blazor WebAssembly application by using the Blazor WebAssembly App project template provided by Microsoft. The final section walks you step by step through the process of creating your own custom Blazor WebAssembly project template. The projects in Chapters 3-7 will use this custom project template. By the end of this chapter, you will be able to create an empty Blazor WebAssembly project.
Chapter 3, Building a Modal Dialog Using Templated Components, provides an introduction to templated components through the creation of a modal dialog component. This chapter is divided into three sections. The first section explains RenderFragment parameters, EventCallback parameters, and CSS isolation. The second section walks you step by step through the process of creating a modal dialog component. The final section walks you step by step through the process of creating your own Razor class library and moving the modal dialog component to it. By the end of this chapter, you will be able to create a modal dialog component and share it with multiple projects through a Razor class library.
Chapter 4, Building a Local Storage Service Using JavaScript Interoperability (JS Interop), provides an introduction to using JavaScript with Blazor WebAssembly through the creation of a local storage service. This chapter is divided into two sections. The first section explains the reasons that you still need to occasionally use JavaScript and how to invoke a JavaScript function from .NET. For completeness, it also covers how to invoke a .NET method from JavaScript. Finally, it introduces the Web Storage API that is used by the project. In the last section, it walks you step by step through the process of creating and testing a service that writes and reads to the local storage of the browser. By the end of this chapter, you will be able to create a local storage service by using JS Interop to invoke JavaScript functions from a Blazor WebAssembly application.
Chapter 5, Building a Weather App as a Progressive Web App (PWA), provides an introduction to progressive web apps through the creation of a simple weather web app. This chapter is divided into two sections. The first section explains what a PWA is and how to create one. It covers both manifest files and service workers. Also, it describes how to use the CacheStorage API, the Geolocation API, and the OpenWeather One Call API, which are required by the project in this chapter. The second section walks you step by step through the process of creating a 5-day weather forecast app and converting it into a PWA by adding a logo, a manifest file, and a service worker. Finally, it shows you how to install and uninstall the PWA. By the end of this chapter, you will be able to convert a Blazor WebAssembly app into a PWA by adding a logo, a manifest file, and a service worker.
Chapter 6, Building a Shopping Cart Using Application State, provides an introduction to application state through the creation of a shopping cart web app. This chapter is divided into two sections. The first section explains application state and Dependency Injection (DI). The last section walks you step by step through the process of creating a shopping cart application. To maintain state in your application, you will create a service that you will register in the DI container and inject into your components. By the end of this chapter, you will be able to use DI to maintain application state within a Blazor WebAssembly app.
Chapter 7, Building a Kanban Board Using Events, provides an introduction to event handling through the creation of a Kanban board web app. This chapter is divided into two sections. The first section discusses event handling, arbitrary parameters, and attribute splatting. The last section walks you step by step through the process of creating a Kanban board application that uses the DragEventArgs class to enable you to drag and drop tasks between the dropzones. By the end of this chapter, you will be able to handle events in your Blazor WebAssembly app and will be comfortable using both attribute splatting and arbitrary parameters.
Chapter 8, Building a Task Manager Using ASP.NET Web API, provides an introduction to hosted Blazor WebAssembly applications through the creation of a task manager web app. This is the first chapter to use SQL Server. It is divided into two sections. The first section describes the components of a hosted Blazor WebAssembly application. It also explains how to use the HttpClient service and the various JSON helper methods to manipulate data. The last section walks you step by step through the process of creating a task manager application that stores its data in a SQL Server database. You will create an API controller with actions, using Entity Framework. By the end of this chapter, you will be able to create a hosted Blazor WebAssembly app that uses the ASP.NET Web API to update data in a SQL Server database.
Chapter 9, Building an Expense Tracker Using the EditForm Component, provides an introduction to the EditForm component through the creation of an expense tracker web app. This chapter uses SQL Server. It is divided into two sections. The first section introduces the EditForm component, the built-in input components, and the built-in validation components. The last section walks you step by step through the process of creating an expense tracker application that uses the EditForm component and some of the built-in components to add and edit the expenses that are stored in a SQL Server database. By the end of this chapter, you will be able to use the EditForm component in conjunction with the built-in components to input and validate data that is stored in a SQL Server database.
We recommend that you read the first two chapters of the book to understand how to set up your computer and how to use the empty Blazor WebAssembly project template. After that, you can complete the remaining chapters in any order. The projects in each chapter become more complex as you proceed through the book. The final two chapters require a SQL Server database in order to complete the project.
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.
This book assumes that you are an experienced web developer. You should have some experience with C# and HTML. Also, all of the projects use Bootstrap 4 as the CSS framework. If you have never used Bootstrap 4, we recommend that you familiarize yourself with it before proceeding, at https://getbootstrap.com/docs/4.6/getting-started/introduction.
There are some projects that use JavaScript and CSS, and two projects that use Entity Framework, but all the code is provided in the book.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Blazor-WebAssembly-by-Example. 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!
Code in Action videos for this book can be viewed at (https://bit.ly/3f1rJ0R).
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781800567511_ColorImages.pdf.
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: "Add the DeleteProduct method to the @code block."
A block of code is set as follows:
private void DeleteProduct(Product product)
{
cart.Remove(product);
total -= product.Price;
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
public class CartService : ICartService
{
public IList<Product> Cart { get; private set; }
public int Total { get; set; }
public event Action OnChange;
}
Any command-line input or output is written as follows:
Add-Migration Init
Update-Database
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: "From the Build menu, select the Build Solution option."
Tips or important notes
Appear like this.
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.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
Blazor WebAssembly is Microsoft's new single-page application (SPA) framework for building web applications on .NET Framework. It enables developers to run C# code on the client. Therefore, instead of being forced to use JavaScript on the browser, we can now use C# on the browser.
In this chapter, we will prepare you to develop web applications using Blazor WebAssembly. We will discuss the two different Blazor hosting models and present the advantages of using Blazor WebAssembly over Blazor Server. Finally, we will guide you through the process of setting up your computer to complete the projects in this book.
In this chapter, we will cover the following topics:
Benefits of using the Blazor frameworkDifferences between the two hosting modelsWhat is WebAssembly?Setting up your PCUsing the Blazor framework has several benefits. For starters, it is a free and open source framework built on Microsoft's robust .NET Framework. Also, it is an SPA framework that uses Razor syntax and can be developed using Microsoft's exceptional tooling.
Blazor is built on .NET Framework. Since Blazor is built on .NET Framework, anyone familiar with .NET Framework can quickly become productive using the Blazor framework. The Blazor framework leverages the robust ecosystem of .NET libraries and NuGet packages from .NET Framework. Also, since both client and server code are written in C#, they can share code and libraries, such as the application logic used for data validation.
Blazor is open source. Since Blazor is a feature of the ASP.NET framework, all of the source code for Blazor is available on GitHub as part of the dotnet/aspnetcore repository that is owned by the .NET Foundation. .NET Foundation is an independent, non-profit organization established to support the innovative, commercially friendly, open source ecosystem around the .NET platform. The .NET platform has a strong community of over 100,000 contributions from more than 3,700 companies.
Blazor is free. Since .NET Framework is free, this means that Blazor is also free. There are no fees or licensing costs associated with using Blazor, including for commercial uses.
The Blazor framework is an SPA framework. As the name implies, an SPA is a web app that consists of a single page. The application dynamically rewrites the single page instead of loading an entirely new page in response to each UI update. The goal is faster transitions that make the web app feel more like a native app.
When a page is rendered, Blazor creates a render tree that is a graph of the components on the page. It is similar to the Document Object Model (DOM) created by the browser. However, it is a virtual DOM. Updates to the UI are applied to the virtual DOM and only the differences between the DOM and the virtual DOM are updated by the browser.
The name of the Blazor framework has an interesting origin story. The term Blazor is a combination of the word browser and the word razor. Razor is the ASP.NET view engine used to create dynamic web pages with C#. Razor is a syntax for combining HTML markup with C# code that was designed for developer productivity. It allows the developer to use both HTML markup and C# in the same file.
Blazor web apps are built using Razor Components. Razor Components are reusable UI elements that contain C# code, markup, and other Razor Components. Razor Components are quite literally the building blocks of the Blazor framework. For more information on Razor Components, refer to Chapter 2, Building Your First Blazor WebAssembly Application.
Important note
Razor Pages and MVC also use the Razor syntax. Unlike Razor Pages and MVC, which render the whole page, Razor Components only render the DOM changes. One way to easily distinguish between them is that Razor components use the RAZOR file extension, while Razor Pages use the CSHTML file extension.
You can use either Microsoft Visual Studio or Microsoft Visual Studio Code to develop Blazor WebAssembly applications. Microsoft Visual Studio is an integrated development environment (IDE), while