【问题标题】:What's a good way to implement Yes/No menus in Asp.Net Core?在 Asp.Net Core 中实现是/否菜单的好方法是什么?
【发布时间】:2020-12-28 18:05:01
【问题描述】:

我正在使用一些 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
}

问:我可以使用更简单、更简洁的语法吗?例如,tag helpers 可以帮忙吗?

提前感谢您的任何建议!

【问题讨论】:

    标签: c# asp.net-core razor


    【解决方案1】:

    Tag helpers 我会这样做。

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

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

    干净、简单、有效。

    【讨论】:

    • 所以没有“自定义标签助手”:只有 HTML“
    • 没错,不需要自定义标签助手。 “asp-for”语法将使“Answers.Q140”的当前值成为“默认”选项。我提供的代码将为您完成这项工作。
    • 完美。我还确认了:1)如果模型不可为空(例如public bool Q140 { get; set; },那么标签助手会自动将“必填字段”验证添加到“选择”元素;2)对于我的“创建”表单,我可以标记任何“选择”选项使其成为默认选项; 3)正如你所说,标签助手将在我的“编辑”表单中自动标记当前值“选定”。好东西 - 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 2010-10-19
    • 2014-10-27
    • 2010-11-23
    • 2019-07-30
    • 1970-01-01
    • 2011-02-23
    相关资源
    最近更新 更多