Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 540
tiger Avatar asked Sep 05 '25 03:09

tiger


1 Answers

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)" />
}
like image 53
itminus Avatar answered Sep 07 '25 20:09

itminus