首页 > 解决方案 > 某些标记语法破坏剃刀解析

问题描述

下面的代码片段打破了剃刀解析和智能感知,你不知道为什么它不起作用(是的,我确实找到了解决方法,但它仍然困扰着我)。

<select class="form-control" @(ViewBag.View ? "disabled" : string.Empty) asp-for="repetitiveness" asp-items="Html.GetEnumSelectList<TaskRepetitiveness>()">
    @if (ViewBag.View)
    {
        <option selected="selected" value="">@(EnumHelper<TaskRepetitiveness>.GetDisplayValue(Model.repetitiveness))</option>
    }
</select>

禁用的案例评估良好,但空字符串案例似乎有问题(以下是使用浏览器测试后的输出):

<select class="form-control" asp-for="repetitiveness" asp-items="Html.GetEnumSelectList<TaskRepetitiveness>()"></select>

这是智能感知在行动:

图片 图片 Ps 它仍然打破了标签助手的大括号:

图片

标签: asp.netasp.net-mvcrazorasp.net-core

解决方案


Razor is only valid within a tag when enclosed within quotes and assigned to an HTML attribute. In other words, something like the following should work:

<select  class="form-control" disabled="@(ViewBag.View as bool? ?? false)" asp-for="repetitiveness" asp-items="Html.GetEnumSelectList<TaskRepetitiveness>()">

This may seem like it won't work because specifying disabled at all causes the field to be disabled, but Razor is smart enough to remove the attribute if it's false.


推荐阅读