Hands-on: A Customer Feedback Form in Blazor
Hands-on: A Customer Feedback Form 📝
Building on our previous exercise on form validation, let's create another practical example: a **Customer Feedback Form**. This demo is simple, relatable, and effectively uses all the same core concepts: a data model with validation rules, an EditForm to bind to the model, and validation components to provide immediate feedback to the user. This reinforces the standard Blazor approach to form handling.
1. The Model: FeedbackModel.cs
First, you'll create a C# class to represent the data for the feedback form. This model holds all the information the user will submit and has **Data Annotation** attributes to enforce validation rules.
// Models/FeedbackModel.cs
using System.ComponentModel.DataAnnotations;
public class FeedbackModel
{
[Required(ErrorMessage = "Your name is required.")]
[StringLength(100, ErrorMessage = "Name cannot exceed 100 characters.")]
public string Name { get; set; } = "";
[Required(ErrorMessage = "A valid email is required.")]
[EmailAddress(ErrorMessage = "Please enter a valid email address.")]
public string Email { get; set; } = "";
[Required(ErrorMessage = "The subject is required.")]
[StringLength(200, ErrorMessage = "Subject cannot exceed 200 characters.")]
public string Subject { get; set; } = "";
[Required(ErrorMessage = "Your message is required.")]
[StringLength(500, ErrorMessage = "The message cannot exceed 500 characters.")]
public string Message { get; set; } = "";
}
Explanation of Data Annotations:
[Required]: Ensures that fields like Name, Email, Subject, and Message cannot be left empty.[EmailAddress]: Automatically checks if the email field is in the correct format (e.g., contains an "@" and a domain).[StringLength]: Prevents string fields (like Name, Subject, and Message) from exceeding a specified maximum length, ensuring data fits your storage requirements.ErrorMessage: Provides custom, user-friendly messages when a validation rule is violated.
2. The Form: FeedbackForm.razor
Next, you create the Blazor page that contains the form itself. This page uses the EditForm component to link the UI inputs to our FeedbackModel and integrates with the validation system.
@page "/feedback"
@using System.ComponentModel.DataAnnotations
@using YourAppName.Models <!-- Replace YourAppName with your actual project name -->
<h3 class="heading3">Submit your Feedback</h3>
<EditForm Model="@feedback" OnValidSubmit="HandleValidSubmit" OnInvalidSubmit="HandleInvalidSubmit">
<DataAnnotationsValidator /> <!-- Activates Data Annotations validation -->
<ValidationSummary class="validation-summary" /> <!-- Displays a summary of all errors -->
<div class="form-group">
<label for="nameInput">Name:</label>
<InputText id="nameInput" @bind-Value="feedback.Name" class="form-control" />
<ValidationMessage For="@(() => feedback.Name)" class="validation-message" />
</div>
<div class="form-group">
<label for="emailInput">Email:</label>
<InputText id="emailInput" @bind-Value="feedback.Email" class="form-control" />
<ValidationMessage For="@(() => feedback.Email)" class="validation-message" />
</div>
<div class="form-group">
<label for="subjectInput">Subject:</label>
<InputText id="subjectInput" @bind-Value="feedback.Subject" class="form-control" />
<ValidationMessage For="@(() => feedback.Subject)" class="validation-message" />
</div>
<div class="form-group">
<label for="messageInput">Message:</label>
<InputTextArea id="messageInput" @bind-Value="feedback.Message" class="form-control" style="height: 120px;" />
<ValidationMessage For="@(() => feedback.Message)" class="validation-message" />
</div>
<button type="submit" class="blazor-button">Send Feedback</button>
</EditForm>
@if (isSubmitted)
{
<p style="color:green; margin-top: 1rem;">✅ Thank you for your feedback, @feedback.Name!</p>
}
@code {
// Create an instance of our FeedbackModel to bind the form to
FeedbackModel feedback = new FeedbackModel();
// Flag to show success message after valid submission
bool isSubmitted = false;
// This method is called when the form is submitted AND all validation rules pass
private void HandleValidSubmit()
{
isSubmitted = true; // Set flag to show success message
Console.WriteLine($"Feedback submitted successfully by {feedback.Name} ({feedback.Email}). Subject: {feedback.Subject}. Message: {feedback.Message}");
// In a real application, you would send this 'feedback' data to a backend API,
// save it to a database, or send an email.
// For demonstration purposes, we just log to the console.
// Optionally, reset the form after successful submission:
// feedback = new FeedbackModel();
}
// This method is called if any validation rules fail upon submission
private void HandleInvalidSubmit()
{
isSubmitted = false; // Ensure success message is not shown
Console.WriteLine("Feedback submission failed due to validation errors.");
// Blazor handles showing the specific error messages automatically via ValidationSummary and ValidationMessage.
}
}
Key Elements Explained:
EditForm Model="@feedback": This line tells theEditFormto bind to ourFeedbackModelobject. Any changes in the input fields will automatically update the properties of thisfeedbackobject.DataAnnotationsValidator: This component is crucial. It activates the validation rules defined by the Data Annotations (like[Required],[EmailAddress]) in yourFeedbackModelclass.ValidationSummary: This component displays a bulleted list of all validation errors that are currently present in the form, providing a quick overview of what needs fixing.ValidationMessage For="@(() => feedback.Name)": EachValidationMessagecomponent is linked to a specific field (e.g.,feedback.Name). It will automatically display that field's specific error message if its validation rules are broken.OnValidSubmit: TheHandleValidSubmitmethod will run only if the user fills out the form correctly, meaning all validation rules pass. This is where you'd typically process the valid data.OnInvalidSubmit: TheHandleInvalidSubmitmethod is called if there are any validation errors when the form is submitted. This simply confirms that the submission was invalid, while theValidationSummaryandValidationMessagecomponents automatically show the user what they need to fix.
🎯 Learning Highlights:
- **Model-Driven Forms:** See how a C# model (`FeedbackModel`) with Data Annotations drives both the structure and validation rules of your form.
- **Automated Validation:** Blazor's `EditForm` and `DataAnnotationsValidator` components handle much of the validation boilerplate, automatically checking rules and updating the UI.
- **Clear User Feedback:** `ValidationSummary` and `ValidationMessage` provide immediate and specific feedback to users about what needs to be corrected.
- **Event-Driven Submission:** The `OnValidSubmit` and `OnInvalidSubmit` events provide clear points to execute logic based on the form's validation state.
- **Reusable Input Components:** `InputText`, `InputTextArea`, etc., simplify binding and integrate seamlessly with the validation system.
This customer feedback form is a practical example of how Blazor streamlines the process of building interactive forms with robust validation, essential for any real-world application.
Comments
Post a Comment