Before you can automate your website deployments, you need to deploy the existing eShop app manually to Azure Kubernetes Service (AKS). You create the Azure resources and deploy the app to AKS using Azure CLI commands and bash scripts. Finally, you create an Azure Active Directory (Azure AD) service principal to allow GitHub Actions to deploy to AKS and Azure Container Registry.
In a form, you should provide instructions to the website user on how to complete each value properly, but you should also check the values that they enter. Blazor provides simple tools that can perform this validation with the minimum of custom code.
In this unit, you learn how to annotate models so that Blazor knows what data to expect. You also learn how to configure a form so it validates and responds to user data correctly.
Validate user input in Blazor forms
When you collect information from a website user, it’s important to check that it makes sense and is in the right form:
For business reasons: Customer information such as a telephone number or order details must be correct to give good service to users. For example, if your webpage can spot a malformed telephone number as soon as the user enters it, you can prevent costly delays later.
For technical reasons: If your code uses form input for calculations or other processing, incorrect input can cause errors and exceptions.
For security reasons: Malicious users might try to inject code by exploiting input fields that aren’t checked.
Website users are familiar with validation rules that check for the presence and correct format of the details they enter. Required fields are often marked with an asterisk or a Required label. If they omit a value or enter a poorly formatted value, they see a validation message instructing them on how to correct the problem. The validation message might appear when the user tabs out of a field or when they select the Submit button.
Here’s an example form where the user submits invalid data. In this case, there are validation messages at the bottom of the form and invalid fields are highlighted in red. You’ll build this form in the next exercise:
It’s a good idea to make validation messages as helpful as possible. Don’t assume any knowledge from the user; for example, not everyone knows the format of a valid email address.
When you use the EditForm component in Blazor, you have versatile validation options available without writing complex code:
In your model, you can use data annotations against each property to tell Blazor when values are required and what format they should be in.
Within your EditForm component, add the DataAnnotationsValidator component, which checks the model annotations against the user’s entered values.
Use the ValidationSummary component when you want to display a summary of all the validation messages in a submitted form.
Use the ValidationMessage component when you want to display the validation message for a specific model property.
Prepare models for validation
Start by telling the DataAnnotationsValidator component what valid data looks like. You declare validation restrictions by using annotation attributes in your data model. Consider this example:
C#Copy
using System.ComponentModel.DataAnnotations;
public class Pizza
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
[EmailAddress]
public string ChefEmail { get; set;}
[Required]
[Range(10.00, 25.00)]
public decimal Price { get; set; }
}
We use this model in a form that enables Blazing Pizza personnel to add new pizzas to the menu. It includes the [Required] attribute to ensure that the Name and Price values are always completed. It also uses the [Range] attribute to check that the price entered is within a sensible range for a pizza. Finally, it uses the [EmailAddress] attribute to check the ChefEmail value entered is a valid email address.
Users enter data using forms. In a classic web app, you create a form using the <form> element, and enable the user to provide data using <input> elements. When the user submits the form, the input can be validated. If the validation is successful, the appropriate actions can then be taken, such as using the information provided to add a new entry to a database or to update a record.
The facilities the <form> and <input> elements provide are simple but relatively primitive. Blazor extends the capabilities of forms with its <EditForm> component. Additionally, Blazor provides a series of specialized input elements that you can use to format and validate the data the user enters.
In this unit, you learn how to use the <EditForm> element and the input elements to build functional forms. You also see how to use data binding with a form.
What is an EditForm?
An EditForm is a Blazor component that fulfills the role of an HTML form on a Blazor page. The main differences between an EditForm and an HTML form are:
Data binding: You can associate an object with an EditForm. The EditForm acts like a view of the object for data entry and display purposes.
Validation: An EditForm provides extensive and extensible validation capabilities. You can add attributes to the elements in an EditForm that specify validation rules. The EditForm applies these rules automatically. This functionality is described in a later unit in this module.
Form submission: An HTML form sends a post request to a form handler when the form is submitted. This form handler is expected to perform the submit process, and then display any results. An EditForm follows the Blazor event model; you specify a C# event handler that captures the OnSubmit event. The event handler performs the submit logic.
Input elements: An HTML form uses an <input> control to gather user input, and a submit button to post the form for processing. An EditForm can use these same elements, but Blazor provides a library of input components that have other features, such as built-in validation and data binding.
Create an EditForm with data binding
The <EditForm> element supports data binding with the Model parameter. You specify an object as the argument for this parameter. The input elements in the EditForm can bind to properties and fields exposed by the model by using the @bind-Value parameter. The following example is based on the WeatherForecast class created by the default Blazor Server App template. The class looks like this:
C#Copy
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
The model for the EditForm is an instance of the WeatherForecast class stored in the @currentForecast variable, and the input elements are bound to the fields in the class:
Most HTML elements expose events that are triggered when something significant happens. Such as, when a page finishes loading, the user clicks a button, or the contents of an HTML element are changed. An app can handle an event in several ways:
The app can ignore the event.
The app can run an event handler written in JavaScript to process the event.
The app can run a Blazor event handler written in C# to process the event.
In this unit, you get a detailed look at the third option; how to create a Blazor event handler in C# to process an event.
Handle an event with Blazor and C#
Each element in the HTML markup of a Blazor app supports many events. Most of these events correspond to the DOM events available in regular web applications, but you can also create user-defined events that are triggered by writing code. To capture an event with Blazor, you write a C# method that handles the event, then bind the event to the method with a Blazor directive. For a DOM event, the Blazor directive shares the same name as the equivalent HTML event, such as @onkeydown or @onfocus. For example, the sample app generated by using the Blazor Server App contains the following code on the Counter.razor page. This page displays a button. When the user selects the button, the @onclick event triggers the IncrementCount method that increments a counter indicating how many times the button was clicked. The <p> element on the page displays the value of the counter variable:
Many event handler methods take a parameter that provides extra contextual information. This parameter is known as an EventArgs parameter. For example, the @onclick event passes information about which button the user clicked, or whether they pressed a button such as Ctrl or Alt at the same time as clicking the button, in a MouseEventArgs parameter. You don’t need to provide this parameter when you call the method; the Blazor runtime adds it automatically. You can query this parameter in the event handler. The following code increments the counter shown in the previous example by five if the user presses the Ctrl key at the same time as clicking the button:
Other events provide different EventArgs parameters. For instance, the @onkeypress event passes a KeyboardEventArgs parameter that indicates which key the user pressed. For any of the DOM events, if you don’t need this information, you can omit the EventArgs parameter from the event handling method.
Now that the code is configured to generate an OpenAPI document file that describes the web API, VanArsdel’s development team turns their attention to publishing the application.
Seamless development experiences in Visual Studio, from code to deploy
In a fusion development team, time is one of the most valuable assets. You write code and build an app, then use different tools to deploy your app. You come back to the code, update it, and switch to the other tools for deployment. The cost for switching between tools is huge, and eventually it decreases your productivity.
What if your development tool, Visual Studio, can do everything for you in one place? It saves time and increases productivity. Visual Studio offers features to publish your app to Azure App Service.
Visual Studio also offers the feature to integrate your web API with Azure API Management while publishing the app.
In the next couple of exercises, you’ll explore how to publish your web API application to Azure App Service and integrate it using Azure API Management.
Template components that you can reuse across multiple apps provide a foundation of tried and tested layout and logic for UI element customization. Template components apply a standardized design across a web app by defining common elements and applying them to all pages. Templates can streamline updates, such as rebranding, because you make modifications only at the central template location.
In this unit, you learn about template components and how you can incorporate them into a Blazor application.
Blazor components have a well-defined lifecycle that starts when they’re first created and ends when they’re destroyed. A set of events that occur in response to specific triggers governs the component lifecycle. Such triggers include the component being initialized, users interacting with the component, or the page where the component resides being closed.
In this unit, you learn about the events that occur during the Blazor component lifecycle. You see how to handle these events to optimize the work done and increase the responsiveness of a Blazor page.
Blazor uses C# components rather than JavaScript to create web pages or HTML sections with dynamic content. But you can use Blazor JavaScript interoperability (JS interop) to call JavaScript libraries in Blazor apps and call JavaScript functions from .NET C# code.
In this unit, you learn how to call JavaScript from C# code in a Blazor page, and how to invoke C# methods from JavaScript functions. In the next unit, you use an alert component from a JavaScript library to update your Blazor pizza delivery website.
Use Blazor JavaScript interoperability
A typical Blazor component uses layout and user interface logic to render HTML at runtime. You use C# code to handle events and other dynamic page features that interact with the user and external services. In many cases, you don’t need to use JavaScript code. Instead, you can use Blazor with .NET libraries, which provide many equivalent capabilities.
However, sometimes you need to use an existing JavaScript library. For example, some open-source JavaScript libraries render components and handle user interface elements in a specialized manner. Or, you might have existing tried and tested JavaScript code that you want to reuse instead of converting it into C#.
You can integrate JavaScript libraries into your applications by using Blazor JavaScript interoperability, or JS interop. You use JS interop to call JavaScript functions from .NET methods and to invoke .NET methods from JavaScript functions. JS interop handles the marshaling of data and object references between Blazor and JavaScript to ease the transition between them.
A task that you often need to perform is packaging libraries for reuse by other developers. NuGet packaging makes it trivial for any developer anywhere to acquire and properly configure all the .NET references for their applications.
In the preceding unit, you built your modal dialog component and used it in your own application. Now you want to reuse it in other applications.
In this unit, you learn the steps necessary to configure a Razor class library as a NuGet package. You also learn how to package the library for distribution by using a package-repository service, such as NuGet.org, or GitHub repositories.
Configure a Razor class library for NuGet packaging
The .NET ecosystem makes it easy to define the properties that are necessary for other developers to identify and use your components. You can define all these properties in the project file (*.csproj) of your Razor class library so they travel with the library. The properties are then updated appropriately when your library is updated.
Components in web applications give developers the ability to reuse portions of an application user interface throughout the application. By using Razor class libraries, developers can share and reuse these components across many applications.
In this unit, you learn how to create a Razor class library. You then use it to share rendered and static content for Blazor applications to customize and display.
Razor class libraries
A Razor class library is a .NET project type. It contains Razor components, pages, HTML, Cascading Style Sheet (CSS) files, JavaScript, images, and other static web content that a Blazor application can reference. Like other .NET class library projects, Razor class libraries can be bundled as a NuGet package and shared on NuGet package repositories such as NuGet.org.
Let’s look at the default template for creating a Razor class library.
Create a project by using the default template
You can optionally begin creating a Razor class library in Visual Studio by selecting File > New Project.
You can also create projects on a command-line interface by running the following command:
.NET CLICopy
dotnet new razorclasslib -o MyProjectName
This template delivers an initial component named Component1, which contains several important features that your components can use:
An isolated cascading style sheet named Component1.razor.css, which is stored in the same folder as Component1.razor. The Component1.razor.css file is conditionally included in a Blazor application that references Component1.
Static content, such as images and JavaScript files, which is available to a Blazor application at runtime and referenced within Component1. This content is delivered in a wwwroot folder that behaves in the same way as a wwwroot folder in an ASP.NET Core or Blazor application.
.NET code, which executes functions that reside in the included JavaScript file.
Differences between a class library and a Razor class library
A class library is a common package delivery structure in .NET applications, and a Razor class library is similar in structure with a few other features configured in the project file.
The project file contains an SDK reference to Microsoft.NET.Sdk.Razor to declare that it contains and creates Razor content as a Razor class library.
The SupportedPlatform entry declares that this library can be used in a browser platform, namely WebAssembly.
The PackageReference to the Microsoft.AspNetCore.Components.Web library gives access to the base Blazor components that are shipped with the framework. This access lets you use those simple components to help you build more complex components.
Razor component contents
This initial Razor component is simple. It contains only an HTML div element with a short block of text:
razorCopy
<div class="my-component">
This component is defined in the <strong>FirstRazorLibrary</strong> library.
</div>