I'm working with some ASP.NET Core 3.1 code where a form has dozens of Y/N menus like this:
<div class="form-group" id="Q3_2_div">
<label>@Questions.Q3_2*</label>
@Html.DropDownListFor(m => m.Answers.Q3_2, new SelectList(Enum.GetValues(typeof(YesNo))),
"Select One",
new { @class = "custom-select", @id = "Answers_Q3_2" })
</div>
Some of the Y/N menus look like this:
<label>@Questions.Q140*</label>
@Html.DropDownListFor(m => m.Answers.Q140,
new SelectList(Enum.GetValues(typeof(YesNo)).OfType<Enum>().Select(x => new SelectListItem
{ Text = Enum.GetName(typeof(YesNo), x), Value = Enum.GetName(typeof(YesNo), x) }),
"Value", "Text", YesNo.No),
null,
new { @class = "custom-select", @id = "Answers_Q140" })
"Yes/No" is defined elsewhere:
public enum YesNo
{
[Display(Name = "Yes")] Yes,
[Display(Name = "No")] No
}
Is there a simpler, less verbose syntax I can use instead? For example, could tag helpers help?
Tag helpers are how I would do it.
My version would probably look something like this:
<select asp-for="Answers.Q140">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
Clean, simple, effective.