My model contains an enum which I'm trying to bind to a list of radio buttons, so that only one value can be selected when the form is submitted.
public enum Options
{
[Display(Name="Option A")
OptionA,
[Display(Name="Option B")
OptionB
}
public class MyModel
{
public Options SelectedOption {get; set;}
public string TextA{get; set;}
public string TextB{get; set;}
}
In MVC 5, I would render a radio button input for each enum value, and the user would be able to select just one. So the code in the view for each radio button would probably look like this:
@Html.RadioButtonFor(m => m.SelectedOption, Options.OptionA)
The problem with MVC6 seems to be that the input tag helper does not support an enum property out of the box. So if I try to add <input asp-for="SelectedOption"/>
, all I get is a textbox.
So my question is, is there a way to do this using an MVC6 tag helper (out of the box or custom) or is there another way to do this? Maybe something like using the old razor syntax or just adding an input tag and populating its attributes?
Please note that ideally there have to be labels for both radio buttons showing the text specified in the enum's [Display]
attributes. Also, only one of the TextA
or TextB
textboxes can appear at the same time and this should be based on the selected radio button, but this is out of the scope of the question. So here's how the rendered markup should look like (more or less):
<div>
<div>
<input id="OptionA" type="radio" name="SelectedOption"/>
<label for="OptionA">Option A</label>
</div>
<div>
<label for="TextA">Text A</label>
<input type="text" id="TextA" name="TextA">
</div>
<div>
<div>
<div>
<input id="OptionB" type="radio" name="SelectedOption"/>
<label for="OptionB">Option B</label>
</div>
<div>
<label for="TextB">Text A</label>
<input type="text" id="TextB" name="TextB">
</div>
<div>
Html.GetEnumSelectList<TEnum>()
to generate the list of options that would be provided as the asp-items value of your new helper. – Parton