Question

How do I use Blazor EditForm with a string value?

Answer and Explanation

To use Blazor's EditForm with a string value, you'll typically bind the EditForm to a model that contains the string. However, if you want to directly bind the EditForm to a single string, you can create a simple model to encapsulate it.

Here’s a step-by-step guide:

1. Create a Simple Model:

Create a class that holds the string value. This class will serve as the model for your EditForm.

public class StringModel
{
  public string Value { get; set; }
}

2. Instantiate the Model:

In your Blazor component, create an instance of this model and initialize the string value.

@code {
  private StringModel model = new StringModel { Value = "Initial Value" };
  private void HandleValidSubmit()
  {
    Console.WriteLine("Submitted Value: " + model.Value);
  }
}

3. Use the EditForm:

Bind the EditForm to the model you created. Use @bind-Value on an InputText component to bind it to the string property in your model.

<EditForm Model="@model" OnValidSubmit="HandleValidSubmit">
  <DataAnnotationsValidator />
  <ValidationSummary />

  <div class="form-group">
    <label for="stringValue">String Value:</label>
    <InputText id="stringValue" class="form-control" @bind-Value="model.Value" />
  <ValidationMessage For="@(() => model.Value)" />
  </div>

  <button type="submit" class="btn btn-primary">Submit</button>
</EditForm>

4. Handle Form Submission:

Implement the HandleValidSubmit method to process the string value when the form is submitted.

Complete Example:

Here's a complete Blazor component:

@page "/"

<EditForm Model="@model" OnValidSubmit="HandleValidSubmit">
  <DataAnnotationsValidator />
  <ValidationSummary />

  <div class="form-group">
    <label for="stringValue">String Value:</label>
    <InputText id="stringValue" class="form-control" @bind-Value="model.Value" />
  <ValidationMessage For="@(() => model.Value)" />
  </div>

  <button type="submit" class="btn btn-primary">Submit</button>
</EditForm>

@code {
  private StringModel model = new StringModel { Value = "Initial Value" };

  private void HandleValidSubmit()
  {
    Console.WriteLine("Submitted Value: " + model.Value);
  }

  public class StringModel
  {
    [Required(ErrorMessage = "Value is required.")]
    public string Value { get; set; }
  }
}

In this example, the StringModel class encapsulates the string value, and the EditForm is bound to an instance of this class. The InputText component uses @bind-Value to create a two-way binding between the input field and the string property. Validation is also included to ensure the string is not empty when the form is submitted.

More questions