You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化这段C# Razor优先级下拉选择框的实现代码?

简化Razor优先级下拉选择框的实现方案

你的原代码存在大量重复逻辑,每个优先级分支都重复渲染相同的选项,不仅冗余还容易出错(比如Red分支里的Green选项漏写了style=")。可以用以下几种更简洁的方式实现:

方法一:通过ViewModel定义选项集合

在你的ViewModel里预先定义好优先级选项集合,把文本、值、颜色统一管理:

public class YourViewModel
{
    public string? Priority { get; set; }

    public List<SelectListItem> PriorityOptions { get; } = new List<SelectListItem>
    {
        new SelectListItem { Text = "Green", Value = "Green", Style = "color: green" },
        new SelectListItem { Text = "Amber", Value = "Amber", Style = "color: orange" },
        new SelectListItem { Text = "Red", Value = "Red", Style = "color: red" }
    };
}

然后在Razor视图里直接遍历这个集合生成选项,自动处理选中状态:

<div class="field">
    <label class="label">Priority</label>
    <select style="width:100%" asp-for="Priority" class="form-select">
        <option></option>
        @foreach (var option in Model.PriorityOptions)
        {
            <option value="@option.Value" 
                    style="@option.Style"
                    @(option.Value == Model.Priority ? "selected" : "")>
                @option.Text
            </option>
        }
    </select>
</div>

方法二:直接在视图内定义选项数组

如果不想修改ViewModel,也可以在视图里直接定义一个匿名类型数组,同样能避免重复代码:

<div class="field">
    <label class="label">Priority</label>
    <select style="width:100%" asp-for="Priority" class="form-select">
        <option></option>
        @{
            var priorities = new[] {
                new { Value = "Green", Text = "Green", Color = "green" },
                new { Value = "Amber", Text = "Amber", Color = "orange" },
                new { Value = "Red", Text = "Red", Color = "red" }
            };
        }
        @foreach (var p in priorities)
        {
            <option value="@p.Value" 
                    style="color: @p.Color"
                    selected="@(p.Value == Model.Priority)">
                @p.Text
            </option>
        }
    </select>
</div>

这两种方式都遵循了DRY(Don't Repeat Yourself)原则,只需要维护一份选项定义,后续修改优先级的文本、颜色或者新增选项都只需要改动一处,逻辑更清晰也不容易出错。

内容的提问来源于stack exchange,提问作者Ollie Shaw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 02:59:54