如何在剃刀中使用三元运算符(特别是在 HTML 属性上)? [英] How to use ternary operator in razor (specifically on HTML attributes)?

查看:28
本文介绍了如何在剃刀中使用三元运算符(特别是在 HTML 属性上)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 WebForms 视图引擎,我通常将三元运算符用于非常简单的条件,尤其是在 HTML 属性中.例如:

With the WebForms view engine, I'll commonly use the ternary operator for very simple conditionals, especially within HTML attributes. For example:

<a class="<%=User.Identity.IsAuthenticated ? "auth" : "anon" %>">My link here</a>

上面的代码将根据用户是否通过身份验证,为 标签赋予一个 authanon 类.

The above code will give the <a> tag a class of auth or anon depending on whether the user is authenticated.

Razor 视图引擎的等效语法是什么?由于 Razor 需要 HTML 标签知道"何时跳入和跳出代码和标记,我目前坚持以下几点:

What is the equivalent syntax with the Razor view engine? Because Razor requires HTML tags to "know" when to jump in and out of code and markup, I'm currently stuck with the following:

@if(User.Identity.IsAuthenticated)  { <a class="auth">My link here</a> }
else { <a class="anon">My link here</a> }

委婉地说,这是可怕的.

我很想做类似的事情,但我很难理解如何在 Razor 中实现:

I would love to do something like this, but am struggling to understand how in Razor:

<a class="@=User.Identity.IsAuthenticated ? "auth" : "anon";">My link here</a>

--

更新:

与此同时,我创建了这个 HtmlHelper:

In the meantime, I've created this HtmlHelper:

public static MvcHtmlString Conditional(this HtmlHelper html, Boolean condition, String ifTrue, String ifFalse)
{
  return MvcHtmlString.Create(condition ? ifTrue : ifFalse);
}

可以从 Razor 中这样调用:

which can be called like this from Razor:

<a class="@Html.Conditional(User.Identity.IsAuthenticated, "auth", "anon")">My link here</a>

不过,我仍然希望有一种方法可以使用三元运算符,而不会退回到将其包装在扩展方法中.

Still, I am hoping there's a way to use the ternary operator without falling back to wrapping it in an extension method.

推荐答案

您应该能够使用 @() 表达式语法:

You should be able to use the @() expression syntax:

<a class="@(User.Identity.IsAuthenticated ? "auth" : "anon")">My link here</a>

这篇关于如何在剃刀中使用三元运算符(特别是在 HTML 属性上)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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