Live Chat Icon For mobile
Live Chat Icon

What is an EditContext and how do I define and use it in a form?

Platform: Blazor| Category : Forms and validation, General

The EditContext of the form stores information about the editing process, such as which fields have been changed and which validation messages are currently displayed. To manually pass the EditContext to the EditForm, follow the steps below.

  1. Create a new Customer.cs file and model Customer class.

    public class Customer
    {
        [Required]
        public string Name { get; set; }
     
        [Required]
        [StringLength(4, ErrorMessage = "The organization code must be less than 5 characters in length.")]
        public string OrganizationCode { get; set; }
    }

  2. Insert an EditForm component into the Index.razor page. Then, make instances of the Customer class and the EditContext, and assign the Customer class instance to the EditContext instance. Finally, bind the EditContext instance to the EditContext property in the EditForm component.

      @page "/"
     
    <EditForm EditContext="@editContext">
        <DataAnnotationsValidator />
        <ValidationSummary />
     
    </EditForm>
     
    @code {
        private Customer _customer = new Customer();
        private EditContext editContext;
     
        protected override void OnInitialized()
        {
            editContext = new(_customer);
        }
    }

  3. As the EditContext stores all the form information, it can be used to validate the form components. Add the Razor code as given below with input  texts and a button. When a form is submitted, the Validate() method is invoked to perform validation.

      @page "/"
     
    <EditForm EditContext="@editContext">
        <DataAnnotationsValidator />
        <ValidationSummary />
        <div class="form-group">
            <label for="name">Name:</>
            <InputText id="name" @bind-Value="_customer.Name" />
            <ValidationMessage For="="@(() => _customer.Name)" />
        </div>
            <div class="form-group">
            <label for="organizationCode">Organization Code:</>
            <InputText id="organizationCode" class="form-control" @bind-Value="_customer.OrganizationCode"/>
            <ValidationMessage For="="@(() => _customer.OrganizationCode)" />
            </div>
        <div style="margin-top: 10px;">
            <button type="submit" class="btn btn-primary" @onclick="Submit">Submit</button>
            </div>
    </EditForm>
    EditContext Output



View Sample in GitHub

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.