Page
1
Exploring Blazor Creating Server-side and Client-side Applications in .NET 9 — Third Edition — Taurius Litvinavicius
Page
2
Exploring Blazor Creating Server-side and Client-side Applications in .NET 9 Third Edition Taurius Litvinavicius
Page
3
Exploring Blazor: Creating Server-side and Client-side Applications in .NET 9, Third Edition ISBN-13 (pbk): 979-8-8688-1523-2 ISBN-13 (electronic): 979-8-8688-1524-9 https://doi.org/10.1007/979-8-8688-1524-9 Copyright © 2025 by Taurius Litvinavicius This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Smriti Srivastava Development Editor: Laura Berendson Editorial Assistant: Jessica Vakili Cover designed by eStudioCalamar Cover image designed by Pexels Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a Delaware LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub. For more detailed information, please visit https://www.apress. com/gp/services/source-code. If disposing of this product, please recycle the paper Taurius Litvinavicius Kaunas, Lithuania
Page
4
(This page has no text content)
Page
5
(This page has no text content)
Page
6
(This page has no text content)
Page
7
(This page has no text content)
Page
8
vii About the Author Taurius Litvinavicius is a distinguished tech expert and author with a strong background in software development. His expertise spans a variety of technologies, including .NET Core, MSSQL, C++, AI, and blockchain. With experience in both business and technology, Taurius has contributed significantly to the tech community through his learning materials in both written and video formats. He is known for his ability to explain complex concepts in a clear and accessible way, making them understandable for both beginners and experienced professionals. “Straightforward” is the word that best describes the approach to all his activities including learning material.
Page
9
ix About the Technical Reviewer Kapil Bansal is a PhD scholar and lead DevOps engineer at S&P Global Market Intelligence, India. He has more than 16 years of experience in the IT industry, having worked on Azure cloud computing (PaaS, IaaS, and SaaS), Azure Stack, DevSecOps, Kubernetes, Terraform, Office 365, SharePoint, release management, application lifecycle management (ALM), Information Technology Infrastructure Library (ITIL), and Six Sigma. He completed a certification program in Advanced Program in Strategy for Leaders from IIM Lucknow and Cyber Security and Cyber Defense from IIT Kanpur. He has worked with companies such as IBM India Pvt Ltd, HCL Technologies, NIIT Technologies, Encore Capital Group, and Xavient Software Solutions, Noida, and has served multiple clients based in the United States, the UK, and Africa, such as T-Mobile, World Bank Group, H&M, WBMI, Encore Capital, and Bharti Airtel (India and Africa). Kapil has also reviewed Hands-On Kubernetes on Azure: Run your applications securely and at scale on the most widely adopted orchestration platform and Azure Networking Cookbook: Practical recipes to manage network traffic in Azure, optimize performance, and secure Azure resources published by Packt as well as Practical Microsoft Azure IaaS: Migrating and Building Scalable and Secure Cloud Solutions and Beginning SharePoint Communication Sites published by Apress and many more.
Page
10
1© Taurius Litvinavicius 2025 T. Litvinavicius, Exploring Blazor, https://doi.org/10.1007/979-8-8688-1524-9_1 CHAPTER 1 Introduction to Blazor In this book, you will learn about Blazor, a modern framework for developing web applications using C#. You’ll learn about all the features of Blazor, from the most basic to the more advanced. You will learn the fundamentals of Blazor syntax and project setup, as well as exciting modern features such as picking files and accessing them using C# in a web browser, accessing API data using JSON, and using many of the other latest features of Blazor. In addition, I will demonstrate what you can achieve in Blazor and provide a few tasks for you to practice yourself, along with the solutions I created for them. Before you start, you need to know and prepare a few things. This is not an introductory book to C# or .NET development, so you should already have good knowledge of C# and be able to build applications with it. It does not matter if you develop back-end applications, Windows applications, or mobile applications; as long as you use C#, you will find something familiar in Blazor. If you haven’t already, you’ll need to install Visual Studio 2022 and make sure that you have the .NET 9 SDK installed on your computer. What Is Blazor? Blazor is a web UI framework that allows you to use C# and .NET on the front end. It allows you to develop your front-end logic in a couple of different ways using the C# programming language, which is something that you will explore later in this chapter.
Page
11
2 Technical aspects aside, think of it this way: in any standard web development project, you would need to have two people, one for the JavaScript and the other for the back end. Sometimes you also need a designer to work with HTML elements and CSS and do other design- related tasks. The Blazor technology will not remove any dependency for a designer, but it will surely remove the dependency on JavaScript. (However, JavaScript can still be used with the Blazor technology.) Blazor uses the Razor syntax (C# mixed with HTML), which will be covered in Chapter 2, so any familiarity with the Razor syntax will give you an edge when developing. There are some differences, though, as you will see shortly. Most important, your C# code in Razor (the .cshtml file) will execute only when the page is loaded, but in Blazor (the .razor file) the code will execute on the loaded page on various events, such as onclick, onchange, and others. Blazor uses WebSocket to communicate with the server as well as work on the server side, or it uses the WebAssembly technology, which allows for C# to be built on the client side. There is also a hybrid approach where essentially both options are used to ensure efficient load times and SEO compatibility. This is where the different types of Blazor technology come into play. What Is WebAssembly? WebAssembly is a technology that allows you to compile languages such as C++ or C# in the browser, thus allowing Blazor to exist. It first appeared as a minimum viable product in early 2017, and while the technology is still in its early years, it is being codeveloped by companies such as Microsoft, Google, Apple, and others. The technology has the support of most major browsers (https://webassembly.org/roadmap/) – Edge, Chrome, Firefox, Opera, and Maxthon (MX) – and the equivalent mobile versions. With its Chapter 1 IntroduCtIon to Blazor
Page
12
3 growth, we can expect the support to be there for a long time. In general, Blazor simply sends a source code file to the browser, and WebAssembly compiles it into a binary file. WebAssembly gives you a safe, sandboxed environment, so it appears similarly as running JavaScript. Nothing is accessible from outside the specific browser tab the user is using. Blazor Render Modes In the current version, there is one Blazor project – “Blazor Web App” (Figure 1-1) – for interactivity (render) modes (formerly known as Blazor types). Figure 1-1. Blazor project template in Visual Studio Chapter 1 IntroduCtIon to Blazor
Page
13
4 The server-side type of Blazor (Figure 1-2) will run all the logic on the server side, mainly using WebSockets to accomplish tasks (Figure 1-1). Although it does give you an ability to use C# to write the front end, this may not be the most efficient option. But from the development perspective, you can eliminate the need for API calls with this option, as you will simply inject your libraries directly to the front-end part. Figure 1-2. Blazor server app template in Visual Studio 2022 The WebAssembly render mode (a.k.a. client-side Blazor) runs directly on the browser (Figure 1-3). You will have your pages on the server, but other than that, the client side handles everything. So, this is great for presentation websites or websites that provide calculators and other such Chapter 1 IntroduCtIon to Blazor
Page
14
5 services. If you need database interactions or if you already have APIs and class libraries, this will not be your choice. It is also not as SEO-friendly as other options. Figure 1-3. Blazor WebAssembly App template in Visual Studio 2022 The next one is essentially a mix of both previous arrangements – auto (See Figure 1-4). This will use some server rendering to load the initial page faster and will then allow the pages to work as WebAssembly render. Chapter 1 IntroduCtIon to Blazor
Page
15
6 Figure 1-4. Blazor Auto template in Visual Studio 2022 Finally, there is the static rendering; any page rendered like that will have no functionality. This is where interactivity location (Figure 1-4) comes into play; you can set global rendering as server, and the whole project will be running as server-side Blazor, but say if you do it per component and do not declare server rendering on certain components, they will be rendered as static – meaning basic html/css, great for landing pages and other such arrangements. Along with these main projects, you will also find a Razor Class Library project (Figure 1-5). This allows you to create Blazor components with all the Blazor features in a code library and if needed publish that to NuGet. Chapter 1 IntroduCtIon to Blazor
Page
16
7 Figure 1-5. Razor Class Library template in Visual Studio 2022 There are also other possible variations of these two types, such as the progressive web application (PWA) option, which allows the Blazor client to run offline. And you can always add API capabilities (controllers and such) to a Blazor server (server rendering mode) project. Summary There is no best type of Blazor; as you have seen throughout this chapter, every option has its own use case. Everything depends on what your project needs right now and, more importantly, what it will need in the future. If you are not sure, simply go with the client-side version, as it will be the most diverse option. In the next chapter, we will dive deeper into Blazor and explore the syntax and some other topics. You will see that while the structure may be different, for the most part, coding happens in the same way for all types of Blazor. Chapter 1 IntroduCtIon to Blazor
Page
17
9© Taurius Litvinavicius 2025 T. Litvinavicius, Exploring Blazor, https://doi.org/10.1007/979-8-8688-1524-9_2 CHAPTER 2 Razor Syntax and the Basics of Blazor This chapter will get you started with Blazor. As mentioned in the previous chapter, all three types of Blazor have a lot in common. Before we can go any further, we will need to look at the syntax and see how it works. Then we will get into the essentials of Blazor, such as bindings and method execution; all of these topics will be used later in the book. In this chapter, you will learn about the following: • Syntax • Element and variable bindings • Method executions • General page events Differences Between Razor and Blazor Simplistically speaking, the difference between Razor and Blazor is that Razor will be executed once on page launch, while the Blazor functionality will work all the time. In other words, the loops and logic statements will get reevaluated in Blazor, while with Razor it will happen only once.
Page
18
10 Syntax As mentioned previously, if you know Razor syntax, you will know Blazor syntax. However, if you do not know Razor syntax, this is the section for you. The Blazor code goes into a markup file named .razor, which contains HTML as well as C# code. Comments Even though we use HTML syntax in a Blazor file, we do not use HTML comments. Instead, we use Razor syntax and get a beautiful and efficient commenting system, with no comments left on a generated page. Listing 2-1 illustrates this. Listing 2-1. Razor/Blazor comment syntax Below is a test p element <p>Test paragraph</p> As shown in Listing 2-1, you simply start a comment section with @* and then end with *@. You can also use the standard HTML comments, but using the Razor/Blazor syntax will be easier to see in the code. The Razor/Blazor comment syntax characters get highlighted, and the actual comment is displayed in green. The comments will not be visible in published app using browser developer tools. Sections Razor syntax is basically C# and HTML code in one file, and while they do interact, you need some higher contrast between the two languages. That is where all the different sections come in; as you will see, the sections are C# dominant, and they are used to highlight the C# parts of the code. Chapter 2 razor Syntax and the BaSiCS of Blazor
Page
19
11 In Listing 2-2, a variable is being declared, and then it is displayed directly in a paragraph using C# code. So, for a single variable and the construction of classes, you can simply use the @ sign and write everything on a single line. If you want to write more than one line for a variable declaration, you need to create a section using @{ ... }. Listing 2-2. Basic Blazor sections string teststring = “tst”; } <p>@teststring</p> At this point, this may look very simple, so let’s dive into a few more examples. In Listing 2-3, the testint variable is declared and set to the value 0, followed by an if statement checking if the value of testint is not 0. Since the statement criteria is not satisfied, whatever is inside the if statement is not displayed. If the testint variable is set to any other value than 0, say 1, the HTML paragraph tag and value would be displayed. The C# code in the @{ } section is highlighted, and it requires no @ sign for each line. The if statement part starts with the @ sign and creates a section similar to the previous example. This means the HTML code in the if statement section is not highlighted in any way. Listing 2-3. if Statement syntax int testing = 0; } @if (testint != 0) { <p>Is not equal to zero</p> } Chapter 2 razor Syntax and the BaSiCS of Blazor
Page
20
12 In Listing 2-4, a for loop has been created, looping five times. Each loop creates a new paragraph tag containing the value for the current iteration, i. The for loop part is highlighted in a slight shade of gray, while the @ signs are highlighted in yellow. The HTML part inside the loop is not highlighted, but the C# code is; that is how you can tell the difference between HTML markup and C# code. Listing 2-4. Syntax coloring @for (int i = 0; I < 5; i++) { <p>@i</p> } Finally, there’s the code section (see Listing 2-5) where all the methods should be declared. The binding variables should also be added to the code section, which you will find later in this chapter (in the “Blazor Binds” section). Listing 2-5. Code section <p>test</p> @code { int a; double b = 2.5; void testmethod() { } } Chapter 2 razor Syntax and the BaSiCS of Blazor