asp.net-core - ASP.NET Core Razor : Conditional attribute without value

标签 asp.net-core razor

我想有条件地渲染 readonly <input> 中的属性。在 Razor 的 ASP.NET Core 方言中,属性的解释与 System.Web.Mvc 略有不同。

在 System.Web.Mvc 中我曾经这样做过:

<input name="Name" class="form-control" @(Model.MyCondition ? "readonly" : "") />

在 ASP.NET Core 中,同样的情况不起作用:没有错误,但属性也没有呈现。

<input asp-for="Name" class="form-control" @(Model.MyCondition ? "readonly" : "" ) />

一旦该属性出现在 HTML 中,它就会被强制执行,因此我无法使用该属性的执行某些操作。此代码片段将导致输入始终为只读:

<input asp-for="Name" class="form-control" readonly="@(Model.MyCondition ? "readonly" : "" )" />

现在,我可以通过创建一个响应 is-readonly 的标签助手来解决这个问题。标签,但这对于如此简单的事情来说似乎非常复杂。

如何有条件地呈现无值属性而不求助于自定义标记助手?

最佳答案

如果在条件不匹配时将该值设置为 null(而不是空字符串),则不会呈现该属性,如下所示:

<input asp-for="Name" class="form-control" readonly="@(Model.MyCondition ? "readonly" : null )" />

关于asp.net-core - ASP.NET Core Razor : Conditional attribute without value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55837409/

相关文章:

asp.net - 如何在 Entity Framework Core 2.1 中播种枚举

asp.net-core - "When using a scoped service, inject the service into the Invoke or InvokeAsync"是什么意思?

asp.net-core - 在 asp.net 核心标识中更改电子邮件异步 "invalid token"

c# - 在 Visual Studio 2019 的 Kestral 下运行 .NET 5 Api 会忽略 launchSettings.json applicationUrl 设置

asp.net-mvc - ASP.Net MVC3 渲染部分操作返回错误

html - 带有razor viewengine的MVC 3中的动态属性值

jquery - 使用模型渲染部分 View 时如何关闭 JQuery UI 对话框

asp.net-core - 电子邮件未确认的用户仍处于登录状态

css - Font Awesome (4.0.3)+ bootstrap(3.0.0)+ asp.net : changing font family

razor - ASP.NET MVC3 (Razor) View 中局部变量的简单增量