使用 Razor MVC3 的条件 HTML 属性 [英] Conditional HTML Attributes using Razor MVC3

查看:18
本文介绍了使用 Razor MVC3 的条件 HTML 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

变量 strCSSClass 通常有一个值,但有时为空.

The variable strCSSClass often has a value but sometimes is empty.

我不想在这个输入元素的 HTML 中包含一个空的 class="",这意味着如果 strCSSClass 是空的,我根本不需要 class= 属性.

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) />

有没有更优雅的方法来做到这一点?具体来说,我可以遵循与元素其他部分相同的语法: class="@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" ?

推荐答案

你不是从我这里听到的,我是 Razor 的 PM,但在 Razor 2(网页 2 和 MVC 4)中,我们将构建条件属性进入 Razor(截至 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,则 class 属性根本不会呈现.

If strCSSClass is null then the class attribute won't render at all.

SSHHH...别说.:)

SSSHHH...don't tell. :)

这篇关于使用 Razor MVC3 的条件 HTML 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆