ASP.NET Core Blazor Forms

Forms are a fundamental part of most web applications, allowing users to input data. Blazor provides a powerful and integrated way to handle forms and user input.

Introduction to Blazor Forms

Blazor allows you to create and manage forms using standard HTML elements combined with Blazor's data binding and event handling capabilities. The core concepts revolve around:

Basic Form Structure

A typical Blazor form involves:

  1. A C# class to hold the form data (a model).
  2. A Blazor component with a <form> element.
  3. Input elements bound to properties of the model.
  4. An event handler for form submission.

Example: A Simple Contact Form Model


public class ContactFormModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Message { get; set; }
}
                

Example: Blazor Component with a Form


@page "/blazor/forms/example"
@using YourApp.Models // Assuming ContactFormModel is in this namespace

Contact Us

@code { private ContactFormModel contactModel = new ContactFormModel(); private void HandleValidSubmit() { // Process the form data here. // For example, send an email, save to database, etc. Console.WriteLine($"Name: {contactModel.Name}"); Console.WriteLine($"Email: {contactModel.Email}"); Console.WriteLine($"Message: {contactModel.Message}"); // Optionally, clear the form or redirect. contactModel = new ContactFormModel(); } }

Key Blazor Form Components and Features

<EditForm> Component

The <EditForm> component is the primary container for forms in Blazor. It manages the form's state, validation, and submission events.

Input Components

Blazor provides several input components that simplify binding to different data types:

These components use the @bind-Value directive for two-way data binding.

<ValidationSummary> and <ValidationMessage>

These components are used to display validation errors:

Server-Side vs. Client-Side Validation

Blazor supports both client-side and server-side validation. For client-side validation, you typically use the Data Annotations library with the DataAnnotationsValidator component.

Note on Validation: For robust validation, it's recommended to decorate your model properties with Data Annotations (e.g., [Required], [EmailAddress], [StringLength]) and include the <DataAnnotationsValidator /> within your <EditForm>.

Handling Form Submission

The OnValidSubmit event handler is where you implement the logic to process the submitted form data. This could involve:

Custom Input Components

For more complex input scenarios, you can create your own custom Blazor input components by inheriting from InputBase<T>.