Overview of Generic Blazor Form
Generic Blazor Mud Form Generation using JSON
1. Overview of Dynamic Form Generation
This code allows for dynamic form generation by using JSON input to create various MudBlazor components (such as text fields, checkboxes, date pickers, etc.). It is flexible enough to create forms that adapt to the data provided and then validate and process user inputs dynamically.
2. Key Components
FormBuilder[] FormBuilders
: This array contains the structure of the forms, including the fields that will be generated dynamically. Each form is built according to the specifications defined in the JSON input (or C# objects representing forms).MudForm
: This is a MudBlazor component used to wrap the entire form. It provides functionality such as validation and form submission.Dictionaries: Various dictionaries are used to store form data (
_formData
,_formDataNumeric
,_formDataBool
,_formDataDateTime
) and map them to form fields.
3. Form Initialization (OnInitializedAsync
)
OnInitializedAsync
)During the initialization phase (OnInitializedAsync
method), the form dynamically reads the structure from FormBuilders
and processes each field according to its InputType
. This determines which type of MudBlazor control to generate. For example:
Text, MultiLine, Email, Password: Text input fields are initialized with default values.
Select, AutoComplete: Initialized with empty values.
CheckBox, Switch: These boolean fields are initialized with
false
.Numeric: Numeric inputs are initialized with
0
.DateTime, Date: Date inputs are initialized with the current date.
These fields are dynamically added to their respective dictionaries based on the InputType
.
4. Dynamic Control Generation
For each field type, a corresponding MudBlazor control is created:
Text:
MudTextField
Select:
MudSelect
Checkbox:
MudCheckBox
Date:
MudDatePicker
Numeric:
MudNumericField
This dynamic form generation allows for the creation of complex forms that are flexible and adaptable based on the input JSON structure.
5. Form Validation and Submission
The SubmitClick_HandlerAsync
method is triggered when the form is submitted. It validates the form and merges the various data types into a single JSON object that can be sent to an API or processed further. This includes:
Merging numeric data into the string-based
_formData
.Converting boolean and datetime data for inclusion in the final JSON output.
Sending the form data back as JSON using
OnSubmit
.
6. Helper Methods
GetFormData
: This method aggregates all form data (including different data types) into one dictionary and serializes it into a JSON string.Event Action Attachments: There are helper methods to attach specific actions to form controls, such as:
AttachCard_EventAction
: Attach event handlers to card components within the form.AutoComplete_EventAction
: Attach auto-complete functionality to a specific field.AttachSubmitButton_EventAction
: Attach a submit action to the form's submit button.AttachFileUpload_EventAction
: Attach file upload functionality to specific fields using browser file input.
7. Handling Special Inputs
File Upload: Special handling is provided for file uploads. The method
AttachFileUpload_EventAction
allows specific actions to be attached to file upload fields, such as uploading a file to a server.AutoComplete: The auto-complete functionality is attached dynamically based on the field configuration.
8. Toggle Password Visibility
There is a small feature for toggling password visibility. This is achieved by changing the input type between password
and text
and updating the icon accordingly (VisibilityOff
and Visibility
).
9. Error Handling and Validation
The form includes error handling via validation functions (ValidationFuncList
), which can be customized for each field. Validation errors are displayed to the user based on the validation results.
In modern web applications, forms are essential components for gathering data from users. In some cases, the form structure may not be static, and you need to generate forms dynamically based on user input or configuration files. In this blog, we’ll explore how to build dynamic forms in a Blazor application using MudBlazor, a UI component library for Blazor that provides material design components.
Overview
In this tutorial, we’ll walk through a real-world solution where forms are generated dynamically from a JSON file or structured object. We’ll cover:
Creating dynamic form components using MudBlazor.
Handling various input types dynamically.
Validating and submitting forms.
Using helper methods to manage event handlers and file uploads.
By the end of this post, you will understand how to dynamically generate forms based on JSON input and how to handle form data in a structured way.
Why Use Dynamic Forms?
Dynamic forms are useful when the form fields are not known ahead of time or may change based on user input, API responses, or configuration files. With dynamic forms, you can:
Adjust form fields on the fly without changing the codebase.
Create reusable forms for different purposes.
Integrate form generation with back-end logic by fetching form configurations from APIs.
Dynamic Form Architecture
The architecture of our dynamic form revolves around two core concepts:
FormBuilder: Defines the structure of the form, including the fields to be generated.
MudForm: A component from MudBlazor that handles form validation and submission.
Key Components in the Code
1. FormBuilder and Field Configuration
At the heart of the dynamic form is the FormBuilder[]
parameter, which specifies the form’s structure. The fields within the FormBuilder
are dynamically created based on their type. The field types are categorized using an enum InputFieldType
:
Text: Single-line or multi-line text input.
Email: Email input field.
Password: Password input field with toggle visibility.
Radio: Radio buttons.
Select: Dropdown selection.
FileUpload: For uploading files.
CheckBox: A checkbox input.
DateTime/Date: Date or date-time picker.
Last updated