👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
Blazor WASM Forms

Blazor WASM Forms

Author - Abdul Rahman (Bhai)

Blazor

34 Articles

Improve

Table of Contents

  1. What we gonna do?
  2. Why we gonna do?
  3. How we gonna do?
  4. Summary

What we gonna do?

In this article, let's learn about how to collect data using forms in Blazor WASM application.

Note: If you have not done so already, I recommend you read the article on Blazor WASM Communication Between Components.

Why we gonna do?

Forms are key part of any web application as they used to collect data from the user and submit to server for further processing. This information might range from the user details that we collect as part of a sign-up process down to a single textbox that allows users to leave comments or post messages in an collaborative application.

How we gonna do?

Introducing EditForm

The Blazor framework renders forms using a built-in component called EditForm. We can bind a model to this component to collect different types of data and process it. Although it is possible to create forms using the standard <form> HTML element, it is recommend to use the EditForm component because of the additional features and benefits it provides.

Note: If you have not done so already, I recommend you read the article on Blazor Wasm Data Binding.

Binding Model with EditForm

To start working with EditForm, we need to create a model class that will hold the data that we want to collect.


<EditForm Model="@starship" OnValidSubmit="@HandleValidSubmit">
    <p>
        <label>
            Identifier:
            <InputText @bind-Value="starship.Identifier" />
        </label>
    </p>
    <p>
        <label>
            Description (optional):
            <InputTextArea @bind-Value="starship.Description" />
        </label>
    </p>
    <p>
        <label>
            Primary Classification:
            <InputSelect @bind-Value="starship.Classification">
                <option value="">Select classification ...</option>
                <option value="Exploration">Exploration</option>
                <option value="Diplomacy">Diplomacy</option>
                <option value="Defense">Defense</option>
            </InputSelect>
        </label>
    </p>
    <p>
        <label>
            Maximum Accommodation:
            <InputNumber @bind-Value="starship.MaximumAccommodation" />
        </label>
    </p>
    <p>
        <label>
            Engineering Approval:
            <InputCheckbox @bind-Value="starship.IsValidatedDesign" />
        </label>
    </p>
    <p>
        <label>
            Production Date:
            <InputDate @bind-Value="starship.ProductionDate" />
        </label>
    </p>

    <button type="submit">Submit</button>

    <p>
        @message
    </p>
</EditForm>

@code {
    public class Starship
    {
        public string? Identifier { get; set; }

        public string? Description { get; set; }

        public string? Classification { get; set; }

        public int MaximumAccommodation { get; set; }

        public bool IsValidatedDesign { get; set; }

        public DateTime ProductionDate { get; set; }
    }

    private Starship starship = new() { ProductionDate = DateTime.UtcNow };
    private string? message = null;

    private void HandleValidSubmit()
    {
        message = "HandleValidSubmit called";

        // Process the valid form
    }
}
        
Demo Space

Binding EditContext with EditForm

An EditForm creates an EditContext based on the assigned model instance as a cascading value for other components in the form. The EditContext tracks metadata about the edit process, including which fields have been modified and the current validation messages.

Assigning to either an EditForm.Model or an EditForm.EditContext can bind a form to data.


<EditForm EditContext="@editContext" OnSubmit="@HandleSubmit">
    <p>
        <label>
            Identifier:
            <InputText @bind-Value="starship.Identifier" />
        </label>
    </p>

    <button type="submit">Submit</button>

    <p>
        @message
    </p>
</EditForm>

@code {
    public class Starship
    {
        public string? Identifier { get; set; }

        public string? Description { get; set; }

        public string? Classification { get; set; }

        public int MaximumAccommodation { get; set; }

        public bool IsValidatedDesign { get; set; }

        public DateTime ProductionDate { get; set; }
    }

    private Starship starship = 
        new()
        {
            Identifier = "NCC-1701",
            Classification = "Exploration",
            MaximumAccommodation = 150,
            IsValidatedDesign = true,
            ProductionDate = new DateTime(2245, 4, 11)
        };
    private EditContext? editContext;
    private string? message;

    protected override void OnInitialized()
    {
        editContext = new(starship);
    }

    private async Task HandleSubmit()
    {
        if (editContext != null)
        {
            message = "HandleSubmit called: Form is valid";

            // Process the valid form
            // await ...
            await Task.CompletedTask;
        }
    }
}
        
Demo Space

Handling Form Submission

When the user submits the form, the EditForm component calls the EditForm.OnSubmit event handler. This event handler is passed the EditContext as a parameter. The EditContext provides access to the EditForm's model and the form's current state.

The EditForm provides the following callbacks for handling form submission:

  • Use OnValidSubmit to assign an event handler to run when a form with valid fields is submitted.
  • Use OnInvalidSubmit to assign an event handler to run when a form with invalid fields is submitted.
  • Use OnSubmit to assign an event handler to run regardless of the form fields' validation status. The form is validated by calling EditContext.Validate in the event handler method. If Validate returns true, the form is valid.

Summary

In this article, we learned what is EditForm and how to use Forms in blazor application by binding either to a Model or to a EditContext.

👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
  • Blazor
  • Forms
  • Model
  • EditContext
  • EditForm