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?
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:
[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)" /> }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With