【发布时间】:2011-05-04 18:12:26
【问题描述】:
对于 WebForms 视图引擎,我通常将三元运算符用于非常简单的条件,尤其是在 HTML 属性中。例如:
<a class="<%=User.Identity.IsAuthenticated ? "auth" : "anon" %>">My link here</a>
上面的代码会给<a>标签一个auth或anon的类,这取决于用户是否被认证。
Razor 视图引擎的等效语法是什么?因为 Razor 需要 HTML 标签来“知道”何时跳入和跳出代码和标记,所以我目前遇到以下问题:
@if(User.Identity.IsAuthenticated) { <a class="auth">My link here</a> }
else { <a class="anon">My link here</a> }
委婉地说,这是可怕。
我很想做这样的事情,但我很难理解在 Razor 中如何:
<a class="@=User.Identity.IsAuthenticated ? "auth" : "anon";">My link here</a>
--
更新:
与此同时,我创建了这个 HtmlHelper:
public static MvcHtmlString Conditional(this HtmlHelper html, Boolean condition, String ifTrue, String ifFalse)
{
return MvcHtmlString.Create(condition ? ifTrue : ifFalse);
}
在 Razor 中可以这样调用:
<a class="@Html.Conditional(User.Identity.IsAuthenticated, "auth", "anon")">My link here</a>
不过,我希望有一种方法可以使用三元运算符,而不会退回到将其包装在扩展方法中。
【问题讨论】:
-
就“最佳实践”而言,我相信您应该使用
new HtmlString("Some stuff here");方法返回类型IHtmlString以获取帮助等... -
请投票here。
标签: razor asp.net-mvc-3