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

查看:384
本文介绍了如何使用三元运算符剃须刀(特别是关于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>

以上code会给&LT; A&GT; 标签的类 AUTH 匿名取决于用户是否经过验证。

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

什么是剃刀视图引擎相当于语法?由于剃刀需要HTML标签知道时跳进出code和标记,我目前坚持了以下内容:

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> }

这是,说得客气一点,的可怕的。

This is, to put it mildly, terrible.

我很想做一些事情的的这一点,但我在努力了解如何在剃刀:

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);
}

可以这样调用从剃刀:

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.

推荐答案

您应该可以使用 @()前pression语法:

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

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

我没有安装剃刀,虽然如此,我可能是错的。还有问题上codePLEX 关于此行为。

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

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