'How to check radiobutton with Enum value in Asp.net core mvc view?

I have rendered my view like below

<div class="row row-margin-zero">
    <label class="radio-inline margin-rightt-ten margin-leftt-five margin-top-none">
        <input type="radio" asp-for="@Model.Countries" name="optradio"  value="1" class="margin-rightt-five">
        America
    </label>
    <label class="radio-inline margin-rightt-ten margin-leftt-five margin-top-none">
        <input type="radio"  asp-for="@Model.Countries" name="optradio" value="2" class="margin-rightt-five">
        Australia
    </label>
    <label class="radio-inline margin-rightt-ten margin-leftt-five margin-top-none">
        <input type="radio"  asp-for="@Model.Countries" name="optradio" value="0" class="margin-rightt-five">
        Eng
    </label>
</div>

Below is my Enum

public Enum Countries {America,Eng,Australia}.

How can i checked the radiobuttons with enum value specified in Model?



Solution 1:[1]

Suppose you have an enum of Countries and also a ViewModel that has a property of Country:

public enum Countries {America, Eng, Australia};

public class XModel{
    // ... other props

    public Countries Country{get;set;}
}

To render radiobuttons for Country, you can get all the possible values by System.Enum.GetValues(typeof(Countries)) such that you can render them all with a simple loop.

@model XModel

@foreach( var c in System.Enum.GetValues(typeof(Countries)) )
{
    <label asp-for="Country">@c</label>
    <input type="radio" asp-for="Country" value="@((int)c)" />
}

Demo:

enter image description here


[Edit]:

how can i show the selected value

Simply add a checked attribute dynamically:

@foreach( var c in System.Enum.GetValues(typeof(Countries)).OfType<Countries>() )
{
    <label asp-for="Country">@c</label>
    <input type="radio" asp-for="Country" value="@((int)c)"  checked="@(c == Model?.Country)" />
}

Solution 2:[2]

I believe <input type='radio'> has some bugs. I recommend using @Html.RadioButtonFor instead.

e.g.

@foreach (var c in System.Enum.GetValues(typeof(Countries)))
{
    <label class="radio-inline margin-rightt-ten margin-leftt-five margin-top-none">
        @(Html.RadioButtonFor<Countries>(m => m.Countries,(Countries)c, null))
        @c
    </label>
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 BrandonStudio