Introduction
In this post, I will demonstrate how to create dynamic InputRadio binding on Enum with Blazor and using C# language, Blazor, and Visual Studio Code.
Creating your Enum
In this sample, I create a simple enum with two entries.
public enum MapInfo {
Department = 2,
City = 4
}
Creating your class to binding
In this stage, I create my class and declare a property of MapInfo type.
public class MyForm {
public MapInfo mapInfo {
get;
set;
}
}
Editing @code of the razor page
In @code, I instantiate MyForm class and declare an array where I stock my enum values.
@code {
private MyForm form = new MyForm();
private Array enumValue = Enum.GetValues(typeof(MapInfo));
}
Creating EditForm in the HTML Section of my razor page
To create a form managed by Razor, I will use an EditForm section. The EditForm models target the object « form » in my @code section. I will also set the OnSubmit parameter (a callback invoked when the form is submitted) to test the result.
If you want information about Razor EditForm, I invite you to visit- Improve how forms and validation work in Blazor web apps - Training | Microsoft Learn.
<EditForm Model="@form" OnSubmit="ValidateRequest">
<InputRadioGroup @bind-Value="form.mapInfo">
@foreach (var option in enumValue)
{
MapInfo enumInfo = (MapInfo)Enum.Parse(typeof(MapInfo), option.ToString());
<InputRadio Value="@enumInfo" /> @option
}
</InputRadioGroup>
</EditForm>
Run and debug with VS Code and Tada the result.
I add the button in my razor page's HTML section to test my InputRadio group and to see if my binding works fine.
<input type="submit" class="btn btn-primary" value="Request" />
Test and validate
When I click on my submit button, the EditForm control callback the ValidateRequest method (of EditForm's OnSubmit parameter) in my @code section.
private async Task ValidateRequest()
{
Console.WriteLine(form.mapInfo.ToString());
await JSRuntime.InvokeVoidAsync("MyJSFunction", new[] {});
}
In my VSCode Debug Console, I can see the enum value selected when I click the Submit button. My property form.mapInfo is a well update. The binding works fine.
See you in my next post.