Skip to main content

This is a new service.

Radios for

Read more about the radios component on the Gov.UK Design System website

Model RadiosForExampleDefaultViewModel.cs

using GovUkDesignSystemDotNet;

public class RadiosForExampleDefaultViewModel
{
    [GovUkValidateRequired(ErrorMessageIfMissing = "Please select a country")]
    public WhereDoYouLiveCountries? WhereDoYouLive { get; set; }

    [GovUkValidateRequiredIf(IsRequiredPropertyName = nameof(OtherCountryRequired), ErrorMessageIfMissing = "Enter the name of the country")]
    public string OtherCountry { get; set; }

    public bool OtherCountryRequired => WhereDoYouLive == WhereDoYouLiveCountries.AnotherCountry;
}

public enum WhereDoYouLiveCountries
{
    England,
    Scotland,
    Wales,
    
    [GovUkRadioCheckboxLabelText(Text = "Northern Ireland")]
    NorthernIreland,
    
    [GovUkRadioCheckboxLabelText(Text = "Another country")]
    AnotherCountry,
}

View RadiosForExampleDefault.cshtml

@using GovUkDesignSystemDotNet
@model RadiosForExampleDefaultViewModel

<form method="post">
    @await Html.GovUkRadiosFor(
        m => m.WhereDoYouLive,
        new RadiosViewModel
        {
            Fieldset = new FieldsetViewModel
            {
                Legend = new FieldsetLegendViewModel
                {
                    HtmlOrText = new HtmlOrText("Where do you live?"),
                    IsPageHeading = true,
                    Classes = ["govuk-fieldset__legend--l"]
                }
            },
        },
        radioItemViewModels: new Dictionary<WhereDoYouLiveCountries, RadioItemViewModel>()
        {
            {
                WhereDoYouLiveCountries.AnotherCountry, new RadioItemViewModel
                {
                    Conditional = new HtmlOrText(
                        @<text>
                             @await Html.GovUkTextInputFor(
                                 m => m.OtherCountry,
                                 new TextInputViewModel
                                 {
                                     Label = new LabelViewModel
                                     {
                                         HtmlOrText = new HtmlOrText("Name of other country")
                                     }
                                 })
                         </text>)
                }
            }
        },
        dividersBefore: new Dictionary<WhereDoYouLiveCountries, string>
        {
            {WhereDoYouLiveCountries.AnotherCountry, "or"}
        }
    )

    @await Html.GovUkButton(new ButtonViewModel
    {
        HtmlOrText = new HtmlOrText("Validate")
    })
</form>

Controller

public IActionResult MyActionName(RadiosForExampleDefaultViewModel viewModel)
{
    if (!ModelState.IsValid)
    {
        return View("RadiosForExampleDefault", viewModel);
    }

    // Do some work with the validated view-model
    return View("InteractiveExampleValidationSuccessful");
}