首页 > 解决方案 > 在 Asp.Net Core 中实现是/否菜单的好方法是什么?

问题描述

我正在使用一些 ASP.Net Core 3.1 代码,其中一个表单有几十个 Y/N 菜单,如下所示:

<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>

一些 Y/N 菜单如下所示:

<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" })  

“是/否”在别处定义:

public enum YesNo
{
    [Display(Name = "Yes")] Yes,
    [Display(Name = "No")] No
}

问:我可以使用更简单、更简洁的语法吗?例如,标签助手可以提供帮助吗?

提前感谢您的任何建议!

标签: c#asp.net-corerazor

解决方案


标签助手是我将如何做到的。

我的版本可能看起来像这样:

<select asp-for="Answers.Q140">
     <option value="Yes">Yes</option>
     <option value="No">No</option>
</select> 

干净、简单、有效。


推荐阅读