ASP.NET Core 7 Razor中的可选非布尔属性

huangapple go评论50阅读模式
英文:

Optional non-boolean attribute in ASP.NET Core 7 Razor

问题

我想根据某些条件使用 <li></li><li aria-current="page"></li>

我尝试了以下代码:

<li @(current == Model.CurrentPage ? @"aria-current=\"page\"" : "") ></li>

这会产生不正确的结果:

<li aria-current=""page""></li>

多年来,Razor 发生了许多变化。在 v7 中,有没有一种简单的 一行代码 方法来实现这个?(不使用多行 if/else 语句、标签助手等。)

(请注意,布尔属性渲染技巧在这里不起作用,因为我希望得到 <li></li> 而不是 <li aria-current=""></li>。)

英文:

I want <li></li> or <li aria-current="page"></li> depending on some condition.

I tried:

<li @(current == Model.CurrentPage ? @"aria-current=\"page\"" : "") ></li>

Which gives the incorrect result:

<li aria-current=""page""></li>

There have been many changes in Razor over the years. In v7, is there an easy one-liner way to do this? (Without multiline if/else statements, tag helpers, etc.)

(Note that the boolean attribute rendering trick doesn't work here, as I want <li></li> rather than <li aria-current=""></li>.)

答案1

得分: 2

我尝试如下:

<li  aria-current=@(current==Model.Page? "page":null )></li>

结果:
ASP.NET Core 7 Razor中的可选非布尔属性

这是你想要的吗?

英文:

I tried as below:

<li  aria-current=@(current==Model.Page? "page":null )></li>

The result:
ASP.NET Core 7 Razor中的可选非布尔属性

Is this what you want?

huangapple
  • 本文由 发表于 2023年2月16日 12:23:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75467847.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定