Skip to main content

This is a new service.

Checkboxes from strings for

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

Model CheckboxesFromStringsForExampleDefaultViewModel.cs

using GovUkDesignSystemDotNet;

public class CheckboxesFromStringsForExampleDefaultViewModel
{
    [GovUkValidateCheckboxNumberOfResponsesRange(ErrorMessageIfNothingSelected = "Select at least one year")]
    public List<string> Years { get; set; } = [];
}

View CheckboxesFromStringsForExampleDefault.cshtml

@using GovUkDesignSystemDotNet
@model CheckboxesFromStringsForExampleDefaultViewModel

@{
    List<int> lastFiveYears = Enumerable.Range(0, 5).Select(i => DateTime.Today.Year - i).ToList();
}

<form method="post">
    @await Html.GovUkCheckboxesFromStringsFor(
        m => m.Years,
        new CheckboxesViewModel
        {
            Fieldset = new FieldsetViewModel
            {
                Legend = new FieldsetLegendViewModel
                {
                    HtmlOrText = new HtmlOrText("Select one or more years to compare"),
                    IsPageHeading = true,
                    Classes = ["govuk-fieldset__legend--l"]
                }
            },
            CheckboxItems = lastFiveYears.Select(year =>
                new CheckboxItemViewModel
                {
                    Value = year.ToString(),
                    Label = new LabelViewModel
                    {
                        HtmlOrText = new HtmlOrText(year.ToString())
                    }
                })
                .ToList()
        }
    )

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

Controller

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

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