Blazor playground

Nova v3.37.0

Preview

Blazor

Fieldradio

← nv-fieldradio

NvFieldradio Component - Practical Guide for Blazor Developers

The NvFieldradio component is a Blazor wrapper around Nova's radio button component, providing seamless integration with Blazor's data binding, forms, and validation systems.

General Blazor Concepts

For general information about data binding, forms, and validation in Nova Blazor components, see the Nova Blazor Integration Guide. This guide focuses on radio button-specific features and patterns.

Basic Usage

Simple Radio Button

razor<NvFieldradio Label="Accept terms" />

Radio Button with Description

razor<NvFieldradio
    Label="I agree to the terms"
    Description="By checking this box, you agree to our terms of service" />

Radio Groups

Radio buttons are typically used in groups where only one option can be selected. Use the same Name attribute for all radio buttons in a group:

Basic Radio Group

razor<fieldset>
    <legend>Select your preferred option:</legend>

    <NvFieldradio Name="preference" Value="option1" Label="Option 1" />
    <NvFieldradio Name="preference" Value="option2" Label="Option 2" />
    <NvFieldradio Name="preference" Value="option3" Label="Option 3" />
</fieldset>

Pre-selected Option

razor<fieldset>
    <legend>Select your preferred option:</legend>

    <NvFieldradio Name="preference" Value="option1" Label="Option 1" Checked />
    <NvFieldradio Name="preference" Value="option2" Label="Option 2" />
    <NvFieldradio Name="preference" Value="option3" Label="Option 3" />
</fieldset>

Two-Way Data Binding

The component supports Blazor's @bind-Checked syntax for seamless two-way data binding:

Simple Binding

razor@code {
    private bool isAgreed = false;
}

<NvFieldradio
    @bind-Checked="isAgreed"
    Label="I agree to the terms" />

<p>Agreed: @isAgreed</p>

Radio Group with Binding

razor<fieldset>
    <legend>Select package size:</legend>

    <NvFieldradio Name="package"
                  Value="small"
                  Label="Small"
                  Checked="@IsSelectedSmall"
                  CheckedChanged="@OnSmallChanged" />

    <NvFieldradio Name="package"
                  Value="medium"
                  Label="Medium"
                  Checked="@IsSelectedMedium"
                  CheckedChanged="@OnMediumChanged" />

    <NvFieldradio Name="package"
                  Value="large"
                  Label="Large"
                  Checked="@IsSelectedLarge"
                  CheckedChanged="@OnLargeChanged" />
</fieldset>

<p>Selected: @selectedValue</p>

@code {
    private string selectedValue = "medium";

    // Computed properties for checked state
    private bool IsSelectedSmall => selectedValue == "small";
    private bool IsSelectedMedium => selectedValue == "medium";
    private bool IsSelectedLarge => selectedValue == "large";

    // Event handlers for each option
    private void OnSmallChanged(bool isChecked)
    {
        if (isChecked)
            selectedValue = "small";
    }

    private void OnMediumChanged(bool isChecked)
    {
        if (isChecked)
            selectedValue = "medium";
    }

    private void OnLargeChanged(bool isChecked)
    {
        if (isChecked)
            selectedValue = "large";
    }
}

Event Handling

Using CheckedChanged Event

razor<NvFieldradio
    Label="Enable notifications"
    CheckedChanged="OnNotificationChanged" />

@code {
    private void OnNotificationChanged(bool isChecked)
    {
        Console.WriteLine($"Notifications {(isChecked ? "enabled" : "disabled")}");
    }
}

Event with Binding

razor@code {
    private bool notificationsEnabled = false;

    private void OnNotificationChanged(bool isChecked)
    {
        notificationsEnabled = isChecked;
        // Additional logic here
        StateHasChanged();
    }
}

<NvFieldradio
    @bind-Checked="notificationsEnabled"
    Label="Enable notifications"
    CheckedChanged="OnNotificationChanged" />

Form Integration

The component integrates seamlessly with Blazor's EditForm for validation and form submission:

Basic Form Integration

razor<EditForm Model="model" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />

    <fieldset>
        <legend>Choose your subscription:</legend>

        <NvFieldradio Name="subscription"
                      Value="basic"
                      Label="Basic Plan"
                      Checked="@model.IsBasicSelected"
                      CheckedChanged="@((bool isChecked) => model.Subscription = isChecked ? "basic" : model.Subscription)" />

        <NvFieldradio Name="subscription"
                      Value="premium"
                      Label="Premium Plan"
                      Checked="@model.IsPremiumSelected"
                      CheckedChanged="@((bool isChecked) => model.Subscription = isChecked ? "premium" : model.Subscription)" />

        <NvFieldradio Name="subscription"
                      Value="enterprise"
                      Label="Enterprise Plan"
                      Checked="@model.IsEnterpriseSelected"
                      CheckedChanged="@((bool isChecked) => model.Subscription = isChecked ? "enterprise" : model.Subscription)" />
    </fieldset>

    <ValidationMessage For="() => model.Subscription" />

    <button type="submit">Submit</button>
</EditForm>

@code {
    private SubscriptionModel model = new();

    private void HandleValidSubmit()
    {
        // Process form submission
    }

    public class SubscriptionModel
    {
        [Required(ErrorMessage = "Please select a subscription plan")]
        public string? Subscription { get; set; }

        public bool IsBasicSelected => Subscription == "basic";
        public bool IsPremiumSelected => Subscription == "premium";
        public bool IsEnterpriseSelected => Subscription == "enterprise";
    }
}

Validation

Required Field Validation

razor<EditForm Model="model" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />

    <fieldset>
        <legend>Choose your option:</legend>

        <NvFieldradio Name="choice"
                      Value="yes"
                      Label="Yes"
                      Checked="@model.IsYesSelected"
                      CheckedChanged="@((bool isChecked) => model.Option = isChecked ? "yes" : model.Option)" />

        <NvFieldradio Name="choice"
                      Value="no"
                      Label="No"
                      Checked="@model.IsNoSelected"
                      CheckedChanged="@((bool isChecked) => model.Option = isChecked ? "no" : model.Option)" />
    </fieldset>

    <ValidationMessage For="() => model.Option" />

    <button type="submit">Submit</button>
</EditForm>

@code {
    private ChoiceModel model = new();

    public class ChoiceModel
    {
        [Required(ErrorMessage = "Please make a selection")]
        public string? Option { get; set; }

        public bool IsYesSelected => Option == "yes";
        public bool IsNoSelected => Option == "no";
    }
}

Custom Validation

razor<EditForm Model="model" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />

    <fieldset>
        <legend>Select experience level:</legend>

        <NvFieldradio Name="experience"
                      Value="beginner"
                      Label="Beginner"
                      Checked="@model.IsBeginnerSelected"
                      CheckedChanged="@((bool isChecked) => model.Experience = isChecked ? "beginner" : model.Experience)" />

        <NvFieldradio Name="experience"
                      Value="intermediate"
                      Label="Intermediate"
                      Checked="@model.IsIntermediateSelected"
                      CheckedChanged="@((bool isChecked) => model.Experience = isChecked ? "intermediate" : model.Experience)" />

        <NvFieldradio Name="experience"
                      Value="advanced"
                      Label="Advanced"
                      Checked="@model.IsAdvancedSelected"
                      CheckedChanged="@((bool isChecked) => model.Experience = isChecked ? "advanced" : model.Experience)" />
    </fieldset>

    <ValidationMessage For="() => model.Experience" />

    <button type="submit">Submit</button>
</EditForm>

@code {
    private ExperienceModel model = new();

    public class ExperienceModel
    {
        [Required]
        [ValidExperienceLevel]
        public string? Experience { get; set; }

        public bool IsBeginnerSelected => Experience == "beginner";
        public bool IsIntermediateSelected => Experience == "intermediate";
        public bool IsAdvancedSelected => Experience == "advanced";
    }

    public class ValidExperienceLevelAttribute : ValidationAttribute
    {
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            var experience = value as string;
            if (string.IsNullOrEmpty(experience))
                return new ValidationResult("Experience level is required");

            var validLevels = new[] { "beginner", "intermediate", "advanced" };
            if (!validLevels.Contains(experience))
                return new ValidationResult("Invalid experience level");

            return ValidationResult.Success;
        }
    }
}

Advanced Scenarios

Dynamic Radio Groups

razor<fieldset>
    <legend>Choose an option:</legend>

    @foreach (var option in options)
    {
        <NvFieldradio Name="dynamic-group"
                      Value="@option.Value"
                      Label="@option.Label"
                      Description="@option.Description"
                      Checked="@IsOptionSelected(option.Value)"
                      CheckedChanged="@(isChecked => OnOptionChanged(option.Value, isChecked))" />
    }
</fieldset>

<p>Selected: @selectedOption</p>

@code {
    private List<OptionItem> options = new()
    {
        new() { Value = "option1", Label = "First Option", Description = "This is the first choice" },
        new() { Value = "option2", Label = "Second Option", Description = "This is the second choice" },
        new() { Value = "option3", Label = "Third Option", Description = "This is the third choice" }
    };

    private string selectedOption = "";

    public class OptionItem
    {
        public string Value { get; set; } = "";
        public string Label { get; set; } = "";
        public string Description { get; set; } = "";
    }

    private bool IsOptionSelected(string value) => selectedOption == value;

    private void OnOptionChanged(string value, bool isChecked)
    {
        if (isChecked)
            selectedOption = value;
    }
}

Conditional Rendering

razor<fieldset>
    <legend>Basic Options:</legend>

    <NvFieldradio Name="plan"
                  Value="basic"
                  Label="Basic Plan"
                  Checked="@IsBasicSelected"
                  CheckedChanged="@OnBasicChanged" />

    <NvFieldradio Name="plan"
                  Value="advanced"
                  Label="Advanced Plan"
                  Checked="@IsAdvancedSelected"
                  CheckedChanged="@OnAdvancedChanged" />
</fieldset>

@if (showAdvancedOptions)
{
    <fieldset>
        <legend>Advanced Options:</legend>

        <NvFieldradio Name="advanced"
                      Value="feature1"
                      Label="Feature 1"
                      Checked="@IsFeature1Selected"
                      CheckedChanged="@OnFeature1Changed" />

        <NvFieldradio Name="advanced"
                      Value="feature2"
                      Label="Feature 2"
                      Checked="@IsFeature2Selected"
                      CheckedChanged="@OnFeature2Changed" />
    </fieldset>
}

@code {
    private string selectedPlan = "";
    private string selectedAdvanced = "";
    private bool showAdvancedOptions = false;

    private bool IsBasicSelected => selectedPlan == "basic";
    private bool IsAdvancedSelected => selectedPlan == "advanced";
    private bool IsFeature1Selected => selectedAdvanced == "feature1";
    private bool IsFeature2Selected => selectedAdvanced == "feature2";

    private void OnBasicChanged(bool isChecked)
    {
        if (isChecked)
        {
            selectedPlan = "basic";
            showAdvancedOptions = false;
            selectedAdvanced = "";
        }
    }

    private void OnAdvancedChanged(bool isChecked)
    {
        if (isChecked)
        {
            selectedPlan = "advanced";
            showAdvancedOptions = true;
        }
    }

    private void OnFeature1Changed(bool isChecked)
    {
        if (isChecked)
            selectedAdvanced = "feature1";
    }

    private void OnFeature2Changed(bool isChecked)
    {
        if (isChecked)
            selectedAdvanced = "feature2";
    }
}

Best Practices

  1. Always use the same Name for radio buttons in the same group
  2. Use meaningful Value attributes that represent the actual data
  3. Provide clear labels for accessibility
  4. Consider using descriptions to provide additional context
  5. Use form validation when the selection is required
  6. Group related radio buttons with <fieldset> and <legend> for better accessibility
  7. Handle edge cases like pre-selection and dynamic options

Common Patterns

Survey/Feedback Forms

razor<fieldset>
    <legend>How satisfied are you with our service?</legend>

    <NvFieldradio Name="satisfaction" Value="very-dissatisfied" Label="Very Dissatisfied" />
    <NvFieldradio Name="satisfaction" Value="dissatisfied" Label="Dissatisfied" />
    <NvFieldradio Name="satisfaction" Value="neutral" Label="Neutral" />
    <NvFieldradio Name="satisfaction" Value="satisfied" Label="Satisfied" />
    <NvFieldradio Name="satisfaction" Value="very-satisfied" Label="Very Satisfied" />
</fieldset>

Settings Panel

razor<div class="settings-panel">
    <h3>Notification Preferences</h3>

    <NvFieldradio @bind-Checked="emailNotifications"
                  Name="notifications" Value="email"
                  Label="Email notifications"
                  Description="Receive updates via email" />

    <NvFieldradio @bind-Checked="pushNotifications"
                  Name="notifications" Value="push"
                  Label="Push notifications"
                  Description="Receive push notifications on your device" />

    <NvFieldradio @bind-Checked="smsNotifications"
                  Name="notifications" Value="sms"
                  Label="SMS notifications"
                  Description="Receive text message updates" />
</div>

@code {
    private bool emailNotifications = true;
    private bool pushNotifications = false;
    private bool smsNotifications = false;
}

Multi-Step Wizard

razor@if (currentStep == 1)
{
    <fieldset>
        <legend>Step 1: Account Type</legend>

        <NvFieldradio Name="account-type"
                      Value="personal"
                      Label="Personal Account"
                      Description="For individual use"
                      Checked="@IsPersonalSelected"
                      CheckedChanged="@OnPersonalChanged" />

        <NvFieldradio Name="account-type"
                      Value="business"
                      Label="Business Account"
                      Description="For organizations and teams"
                      Checked="@IsBusinessSelected"
                      CheckedChanged="@OnBusinessChanged" />
    </fieldset>
}

@code {
    private int currentStep = 1;
    private string accountType = "";

    private bool IsPersonalSelected => accountType == "personal";
    private bool IsBusinessSelected => accountType == "business";

    private void OnPersonalChanged(bool isChecked)
    {
        if (isChecked)
            accountType = "personal";
    }

    private void OnBusinessChanged(bool isChecked)
    {
        if (isChecked)
            accountType = "business";
    }
}

Troubleshooting

Radio buttons not grouping properly

  • Ensure all radio buttons in the same group have the same Name attribute
  • Check for typos in the Name property

Two-way binding not working

  • For single radio buttons, use @bind-Checked="yourBooleanVariable"
  • For radio groups, use Checked="@IsSelected..." with computed properties and CheckedChanged="@OnChanged..." event handlers
  • Each radio button in a group should have its own event handler that updates the selected value

Form validation not triggering

  • Ensure you're using EditForm with DataAnnotationsValidator
  • Add the For parameter pointing to your model property
  • Use [Required] attribute for mandatory selections

Event not firing

  • Use CheckedChanged event callback
  • Remember that changing Checked programmatically won't trigger the event
  • Use StateHasChanged() if you need to update the UI after event handling

This guide covers the most common use cases and patterns for the NvFieldradio component in Blazor applications. For more advanced scenarios or specific requirements, refer to the component's API documentation or the Storybook examples.