Hello!

Let’s see how you can create a form in BlazorServer. Start with the model. I will create a file Models/User.cs, which will contain fields for the form.

namespace BlazorLearn.Models
{
    public class User
    {
        public string UserName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public int Age { get; set; }
        public string Gender { get; set; }
    }
}

For the model to be available in razor components, it must be added to _Imports.razor as @using BlazorLearn.Models.

Basic Form

Now I will create the razor component Register.razor which will contain the form. To be able to open the form in the browser, I will add @page "/register" at the top of the component. In the code section you need to create a new object of class User, as well as an empty string in which the data will be written after the submission of the form. And I will add <p>@_formResult</p> to display the data entered after the submission.

Now let’s move on to the form itself.

In blazor, the form is created using the EditForm tag to which you want to pass the model. We have an object of type User which is created in the section code - <EditForm Model = "_user"></EditForm>. Now you need to add input fields to the form. For text tag will be <InputText></InputText> for other data types have their own tags, for example InputNumber for numeric types. I will add an input field for each element of the model. You can also call a method on events like OnValidSubmit or OnInvalidSubmit. For this purpose I will make a method HandleValidSubmit which will write UserName and LastName from the form to empty string which was created in code section.

@page "/register"

<p>@_formResult</p>

<EditForm Model="_user" OnValidSubmit="HandleValidSubmit" On>
    <InputText id="UserName" @bind-Value="_user.UserName"></InputText>
    <InputText id="LastName" @bind-Value="_user.LastName"></InputText>
    <InputText id="Email" @bind-Value="_user.Email"></InputText>
    <InputSelect id="Gender" @bind-Value="_user.Gender">
        <option value="">Select Gender</option>
        <option value="1">Male</option>
        <option value="2">Female</option>
    </InputSelect>
    <InputNumber id="Age" @bind-Value="_user.Age"></InputNumber>
    <button class="btn btn-primary" type="submit">Submit</button>
</EditForm>

@code {
    private User _user = new User();
    private string _formResult = "";

    private void HandleValidSubmit()
    {
        _formResult = $"{_user.UserName}, {_user.LastName} was created";
    }
}

FormNoValidation

The form works, but in the Age field I entered -30 and no validation took place. Let’s now add validation

Form Validation

Validation is added using attributes. Let’s go back to the model and make some changes.

using System.ComponentModel.DataAnnotations;

namespace BlazorLearn.Models
{
    public class User
    {
        [Required]
        [StringLength(maximumLength: 20, MinimumLength = 5, ErrorMessage = "Invalid UserName length")]
        public string UserName { get; set; }
        [Required]
        [StringLength(maximumLength: 10, MinimumLength = 5, ErrorMessage = "Invalid LastName length")]
        public string LastName { get; set; }
        [Required]
        [EmailAddress(ErrorMessage = "Provide a valid email address")]
        public string Email { get; set; }
        [Required]
        [Range(1, 100, ErrorMessage = "You need to enter valid range")]
        public int Age { get; set; }
        public string Gender { get; set; }
    }
}

Length validation is now enabled for UserName and LestName and these fields are also required. Email validation has been added for Email. And for Age added validation for number between 1 and 100. These fields are also required. No validation has been added for the Gender field.

In order for validation to work place, you need to add a <DataAnnotationsValidator></DataAnnotationsValidator> tag to the form.

FormNoMessage

Now the validation works but no messages are displayed when validation failed. I will add another tag <ValidationSummary></ValidationSummary> to form. As a result, the form will look like this

@page "/register"

<p>@_formResult</p>

<EditForm Model="_user" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator></DataAnnotationsValidator>
    <ValidationSummary></ValidationSummary>
    <label>
        First Name:
        <InputText id="UserName" @bind-Value="_user.UserName"></InputText>
    </label>
    <label>
        Last Name:
        <InputText id="LastName" @bind-Value="_user.LastName"></InputText>
    </label>
    <label>
        Email:
        <InputText id="Email" @bind-Value="_user.Email"></InputText>
    </label>
    <label>
        Gender:
        <InputSelect id="Gender" @bind-Value="_user.Gender">
            <option value="">Select Gender</option>
            <option value="1">Male</option>
            <option value="2">Female</option>
        </InputSelect>
    </label>
    <label>
        Age:
        <InputNumber id="Age" @bind-Value="_user.Age"></InputNumber>
    </label>
    <button class="btn btn-primary" type="submit">Submit</button>
</EditForm>

@code {
    private User _user = new User();
    private string _formResult = "";

    private void HandleValidSubmit()
    {
        _formResult = $"{_user.UserName}, {_user.LastName} was created";
    }
}

FinalResult