Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor InputRadio

When we are in a InputRadioGroup, how to have a radio button checked by default? This does not seem to work:

<InputRadio class="mr-1" Name="Selected" Value="@("General")" checked="checked"></InputRadio>
like image 778
user3656651 Avatar asked Sep 07 '26 18:09

user3656651


2 Answers

The value of the @bind-Value="@_model.SelectedManufacturer" in the InputRadioGroup sets the value of the group and the code below will set the selected radio button to tesla at the start as that is what it is set to in the FormClass

<EditForm Model="_model">
    <InputRadioGroup @bind-Value="@_model.SelectedManufacturer">
        Manufacturer:
        <br>
        @foreach (var manufacturer in Manufacturers)
        {
            <InputRadio Value="manufacturer" />
            @manufacturer
            <br>
        }
    </InputRadioGroup>
</EditForm>


@code {

   List<String> Manufacturers = new List<string> { "Ford", "Toyota", "Tesla" };

   FormClass _model = new FormClass();

   class FormClass
    {
      public  String SelectedManufacturer { get; set; } = "Tesla";
    }
}
like image 137
David Masterson Avatar answered Sep 12 '26 21:09

David Masterson


I had this problem in .net 8 blazor SSR , I resolved by using input tag with type="radio" and name="vm.TermsOfDelivery" and value="1" and checked manually. Also I used bootstrap classes.

<EditForm Model="vm" method="post" OnValidSubmit="Submit" FormName="loi" Enhance>

            <div class="mb-3">
                Terms of Delivery:
                <input id="r1" class="form-check-input ms-2 pointer" type="radio" name="vm.TermsOfDelivery" value="1" checked="@(vm.TermsOfDelivery==1)">
                <label class="form-check-label pointer" for="r1" >Exwork</label>
                <input id="r2" class="form-check-input ms-2 pointer" type="radio" name="vm.TermsOfDelivery" value="2" checked="@(vm.TermsOfDelivery==2)">
                <label class="form-check-label pointer" for="r2">FOB</label>
                <input id="r3" class="form-check-input ms-2 pointer" type="radio" name="vm.TermsOfDelivery" value="3" checked="@(vm.TermsOfDelivery==3)">
                <label class="form-check-label pointer" for="r3">CFR</label>
            </div>

public class LoiAddVm
{
    public byte TermsOfDelivery { get; set; }
}

[SupplyParameterFromForm]
public LoiAddVm vm { get; set; } = new() { TermsOfDelivery = 1 };

the name="vm.TermsOfDelivery" because the InputRadioGroup of Microsoft expect it. vm is the name of EditForm Model that binds by [SupplyParameterFromForm] attribute.

Also after post to the server if validations in not valid we must set checked conditionally: checked="@(vm.TermsOfDelivery==1)"

enter image description here

like image 26
M Komaei Avatar answered Sep 12 '26 20:09

M Komaei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!