用剃刀MVC3条件HTML属性 [英] Conditional HTML Attributes using Razor MVC3
问题描述
变量strCSSClass往往有一个值,但有时是空的。
The variable strCSSClass often has a value but sometimes is empty.
我不希望包括空类=在此输入元素的HTML,这意味着如果strCSSClass是空的,我不希望类=属性都没有。
I do not want to include an empty class="" in this input element's HTML, which means if strCSSClass is empty, I don't want the class= attribute at all.
下面是做一个有条件的HTML属性的一种方式:
The following is one way to do a conditional HTML attribute:
<input type="text" id="@strElementID" @(CSSClass.IsEmpty() ? "" : "class=" + strCSSClass) />
是否有这样做的更优雅的方式?具体来说之一,我可以按照相同的语法元素中的其他部分使用:类=@ strCSSClass
Is there a more elegant way of doing this? Specifically one where I could follow the same syntax as is used in the other parts of the element: class="@strCSSClass" ?
推荐答案
您没听到我的心声,为剃刀的PM,但在剃刀2(网页2和MVC 4)我们必须条件属性建到剃须刀(如MVC 4 RC的测试成功),所以你只能说这样的事情...
You didn't hear it from me, the PM for Razor, but in Razor 2 (Web Pages 2 and MVC 4) we'll have conditional attributes built into Razor(as of MVC 4 RC tested successfully), so you can just say things like this...
<input type="text" id="@strElementID" class="@strCSSClass" />
如果strCSSClass为null,则类属性将不会呈现在所有。
If strCSSClass is null then the class attribute won't render at all.
SSSHHH ......不要告诉。 :)
SSSHHH...don't tell. :)
这篇关于用剃刀MVC3条件HTML属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!