我想有条件地渲染 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/