<div class="field">
    <label class="label">
        Priorirty
    </label>
    <select style="width:100%" asp-for="Priority" class="form-select">
        @if (Model.Priority == "Green")
        {
            <option></option>
            <option selected="selected" style="color: green" value="Green">Green</option>
            <option style="color: orange" value="Amber">Amber</option>
            <option style="color: red" value="Red">Red</option>
        }
        @if (Model.Priority == "Amber")
        {
            <option></option>
            <option style="color: green" value="Green">Green</option>
            <option selected="selected" style="color: orange" value="Amber">Amber</option>
            <option style="color: red" value="Red">Red</option>
        }
        @if (Model.Priority == "Red")
        {
            <option></option>
            <option color: green" value="Green">Green</option>
            <option style="color: orange" value="Amber">Amber</option>
            <option selected="selected" style="color: red" value="Red">Red</option>
        }
        @if (Model.Priority == null)
        {
            <option></option>
            <option style="color: green;" value="Green">Green</option>
            <option style="color: orange;" value="Amber">Amber</option>
            <option style="color: red" value="Red">Red</option>
        }
    </select>
</div>

做这样的事.有没有更简单的方法来做这件事?我对剃须刀的语法还很陌生

我什么都没试过

推荐答案

如果将表达式传递给计算结果为falsenull的HTML属性,则根本不会呈现该属性.

   <select style="width:100%" asp-for="Priority" class="form-select">  
      <option></option>
        <option selected="@(Model.Priority == "Green")" style="color: green" value="Green">Green</option>
        <option selected="@(Model.Priority == "Amber")" style="color: orange" value="Amber">Amber</option>
        <option selected="@(Model.Priority == "Red")" style="color: red" value="Red">Red</option>
    </select>

但实际上,您根本不需要设置selected属性值.通过为Model.Priority赋值, Select 标记帮助器将为您完成此操作,因为您为该属性设置了asp-for属性.

Csharp相关问答推荐

无法将blob发送到Azure -缺少HTTP标头异常

Microsoft. VisualBasic. FileIO. FileSystem. MoveFile()对话框有错误?

Blazor. NET 8—阶段启动配置文件不启动网站VS2022

为什么将鼠标悬停在DateTimeOffset上只显示Hour值?

如何在NodaTime中为Instant添加一年?

使页面内容居中

从.Net 6 DLL注册和检索COM对象(Typelib导出:类型库未注册.(异常来自HRESULT:0x80131165))

我想在文本框悬停时在其底部显示一条线

如何使用C#获取FireStore中的列表输出文档

Unix上的.NET(核心):.NET意外地未看到通过P/Invoke系统调用对环境变量进行的进程内修改

HttpClient 415不支持的媒体类型错误

Automapper 12.x将GUID映射到字符串

.NET 8 DI GetServices<;对象&>不工作

单元测试类型为HttpClient with Microsoft.Extensions.Http.Resilience

如何在Polly重试策略成功之前将HttpClient请求排队?

使用可空引用类型时C#接口实现错误

Xamarin Forms应用程序中登录页面的用户名和密码编辑文本之间不需要的空格

如何使用moq和xUnit对删除操作进行单元测试?

我应该使用IMhemyCache来存储承载令牌,还是应该为Azure函数中的401个错误实施Polly重试策略?

MudRadioGroup不切换