In part, we are going to learn how to create radio buttons with a blazor.

If you are new to Blazor, then you must see

Here we have Already Created an application in Blazor Part 1.

Complete Source Code on Github

Below is a Snapshot of the Application that we have created

Adding ViewModel Folder

Adding the ViewModel folder to the project.

Adding ViewModel

Adding ViewModel with the class name RadioButtonViewModel, which will have string and collection property in it.

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace BlazorPlayGround1.ViewModel
{
    public class RadioButtonViewModel
    {
        [Required(ErrorMessage = "Select Gender")]
        public string SelectedGender { get; set; }
        public List<SelectListItem> ListofGender { get; set; }
    }
}

In following, the step we are going to add a Component.

Adding Component

We are going to add a Component with the name RadioButtonComponent.razor.

Adding Base Class for RadioButtonComponent Component

We will add a class with the name RadioButtonComponentBase, and then we will inherit it with ComponentBase.

Next, we will add the RadioButtonViewModel property in the RadioButtonComponentBase component and SelectedValue property, which displays selected value text on the Page.

using BlazorPlayGround1.ViewModel;
using Microsoft.AspNetCore.Components;

namespace BlazorPlayGround1.Pages
{
    public class RadioButtonComponentBase : ComponentBase
    {
        protected RadioButtonViewModel RadioButtonViewModel { get; set; } = new RadioButtonViewModel();
        protected string SelectedValue { get; set; }
    }
}

Next step, we need to call the ListofGender method inside the OnInitialized method to initialize the RadioButtonViewModel property.

INITIALIZING LISTOFGENDER IN ONINITIALIZED METHOD

protected override void OnInitialized()
{
      var defaultgender = "1";
      RadioButtonViewModel.ListofGender = new List<SelectListItem>()
      {
          new SelectListItem()
          {
              Value ="1",
              Text = "Male"
          },
          new SelectListItem()
          {
              Value = "2",
              Text ="Female"
          },
          new SelectListItem()
          {
              Value = "3",
              Text ="Others"
          }
      };
            
     RadioButtonViewModel.SelectedGender = defaultgender;
     SetGenderDisplayValue(defaultgender);
}

After initializing next, we have 3 things to do

  1. We should display the value of the selected radio button. For that, we need to use the ValueChanged properties of InputRadioGroup.
  2. On form Submit, we should be able to get the value of the selected Radio button.

For that, we are going to add 3 Methods to RadioButtonComponentBase Class.

  • SetGenderDisplayValue, Which is used to display selected radio button text value.
  • SelectionChanged
  • FormSubmitted

SetGenderDisplayValue

This method takes the value as input and sets SelectedValue Property used on the Page for displaying Selected Value.

private void SetGenderDisplayValue(string value)
{
    if (value == "1")
    {
        SelectedValue = "Male";
    }
    else if (value == "2")
    {
        SelectedValue = "Female";
    }
    else if (value == "3")
    {
        SelectedValue = "Others";
    }
}

SelectionChanged

This method is called when we change dropdown selection. Here we pass value to SetGenderDisplayValue method for setting display text.

Also, we assign the value which we have received to the SelectedGender property.

 protected void SelectionChanged(string value)
 {
     if (value != null)
     {
         SetGenderDisplayValue(value);
         RadioButtonViewModel.SelectedGender = value;
     }
 }

Form Submitted

This method is called on form submit, where we can read the selected value of the radio button.

protected void FormSubmitted()
{
    var radiobuttonValue = RadioButtonViewModel.SelectedGender;
}

Complete RadioButtonComponentBase.cs code-behind code

using System.Collections.Generic;
using BlazorPlayGround1.ViewModel;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace BlazorPlayGround1.Pages
{
    public class RadioButtonComponentBase : ComponentBase
    {
        protected RadioButtonViewModel RadioButtonViewModel { get; set; } = new RadioButtonViewModel();
        protected string SelectedValue { get; set; }
        protected override void OnInitialized()
        {
            var defaultgender = "1";
            RadioButtonViewModel.ListofGender = new List<SelectListItem>()
            {
                new SelectListItem()
                {
                    Value ="1",
                    Text = "Male"
                },
                new SelectListItem()
                {
                    Value = "2",
                    Text ="Female"
                },
                new SelectListItem()
                {
                    Value = "3",
                    Text ="Others"
                }
            };
            RadioButtonViewModel.SelectedGender = defaultgender;
            SetGenderDisplayValue(defaultgender);
        }


        protected void SelectionChanged(string value)
        {
            if (value != null)
            {
                SetGenderDisplayValue(value);
                RadioButtonViewModel.SelectedGender = value;
            }
        }

        protected void FormSubmitted()
        {
            var radiobuttonValue = RadioButtonViewModel.SelectedGender;
            SetGenderDisplayValue(radiobuttonValue);
        }

        private void SetGenderDisplayValue(string value)
        {
            if (value == "1")
            {
                SelectedValue = "Male";
            }
            else if (value == "2")
            {
                SelectedValue = "Female";
            }
            else if (value == "3")
            {
                SelectedValue = "Others";
            }
        }
    }
}

In this part, we will work on RadioButtonComponent.razor page, which we have added earlier.

SETTING UP RADIOBUTTONCOMPONENT.RAZOR PAGE

  1. Going to add the @page Razor directive and specify the route for Component (RadioExample)
  2. Adding @inherits directive and set base class for component (RadioButtonComponentBase).
  3. Adding Edit form which Renders a form element and set Model and OnValidSubmit Properties of it.
  4. Adding InputRadioGroup and setting ValueChanged, ValueExpression, Value, which are used for 2-way data binding.

ValueChanged=”@((string value) => SelectionChanged(value))”

ValueExpression=”@(() => RadioButtonViewModel.SelectedGender)”

Value=”@RadioButtonViewModel.SelectedGender”

  • Using the foreach loop, we are going to add Input Radio to InputRadioGroup.

At last, we are displaying the value of the selected dropdown @SelectedValue

RadioButtonComponent.razor Page

@page "/RadioExample"
@inherits RadioButtonComponentBase

<EditForm Model="@RadioButtonViewModel" OnValidSubmit="@FormSubmitted">
    <div class="card">
        <div class="card-header">
            <h5 class="card-title">RadioButton</h5>
        </div>
        <div class="card-body">
            <div class="form-row">
                <div class="form-group col-md-4">
                    <label>Gender: </label>
                    <br />
                    <ValidationMessage For="@(() => RadioButtonViewModel.SelectedGender)" />
                    <InputRadioGroup ValueChanged="@((string value) => SelectionChanged(value))"
                                     ValueExpression="@(() => RadioButtonViewModel.SelectedGender)"
                                     Value="@RadioButtonViewModel.SelectedGender"
                                     class="form-control">
                        @foreach (var gender in RadioButtonViewModel.ListofGender)
                        {
                            <InputRadio Value="gender.Value" />@gender.Text <br />
                        }
                    </InputRadioGroup>
                </div>
             
            </div>
        </div>
        <div class="card-footer">

            <button type="submit" class="btn btn-success">Submit</button>
            Selected:- @SelectedValue
        </div>
    </div>
</EditForm>

In the Next Step, Let Press F5 to run the project, and you will see the output.

By Saineshwar Bageri

I am Microsoft MVP | C# Corner MVP | Code Project MVP | FULL STACK .NET Developer and working on .Net Web Technology (Asp.net, Asp.net Core,.Net Core, C#, Sqlserver, MVC, Windows, Console Application, javascript, jquery, json, ORM Dapper) and also a freelance developer.