【问题标题】:How to use ternary operator in cshtml page. (Razor View Engine) [duplicate]如何在 cshtml 页面中使用三元运算符。 (Razor View 引擎)[重复]
【发布时间】:2019-02-06 12:20:51
【问题描述】:

我正在处理 .cshtml 页面。 我想通过从 Session 变量中获取值来有条件地显示一些 html。 如果我在 cshtml 页面中使用 if else 条件,它可以工作,但我想用三元运算符替换它。

这是工作代码:-

    @if (HttpContext.Current.Session["RequestCount"] != null)
     {
       if (HttpContext.Current.Session["RequestCount"].ToString() != "0")
          {
            <li class="nav-item"><a class="nav-link ripple" href="@Url.Action("Images", "Admin")"> <i class="icon-bell-ring" style="position:relative"><em>@HttpContext.Current.Session["RequestCount"].ToString() </em></i><span>Images Request</span> </a> </li> 
          }
       else
          {
            <li class="nav-item"><a class="nav-link ripple" href="@Url.Action("Images", "Admin")"> <i class="icon-bell-ring"></i> <span>Images Request</span> </a> </li>
          }
     }

尝试使用三元运算符:-

  <li class="nav-item"><a class="nav-link ripple" href="@Url.Action("Images","Admin")"> <i class="icon-bell-ring" style="position:relative">@HttpContext.Current.Session["RequestCount"].ToString) != "0" ?<em>@HttpContext.Current.Session["RequestCount"].ToString(): &nbsp; </em></i><span>Images Request</span> </a> </li>

【问题讨论】:

  • 首先,您遇到了什么错误?其次,看起来您在三元的一个分支中有一个打开的&lt;em&gt; 标签,而在第二个分支中有一个关闭的标签。尝试更好地格式化该行,它可能会变得很明显为什么它不起作用。此外,括号可能更容易指示三元的结尾应该在哪里。
  • 谢谢@Becuzz,错误是它不能有条件地工作,它显示两个html。 prntscr.com/kp3g0j
  • 如果会话值 == "0",我想隐藏红色气泡。

标签: model-view-controller


【解决方案1】:

如果你想使用三元运算符,你需要做几件事。

  1. 用括号括起来。正如您所写的那样,? 被解释为文本,而不是运算符。所以从这样的开始:

    @(myCondition ? "a" : "b")

  2. 不要把开始标签放在运算符里面(除非你把结束标签也放进去)。所以像这样把em标签移到外面。

    &lt;em&gt;@(/* ternary operator here */)&lt;/em&gt;

  3. 最后,确保两个分支的返回类型相同。在您的示例中,您试图在一个部分(HttpContext 位)中返回一个常规字符串,第二个部分您试图返回一个不间断的空格(我假设您不希望文字文本 &amp;nbsp; 输出到这页纸)。所以将它们都包装在HtmlStrings 中。

所以当所有这些放在一起时,你会得到这样的东西(下面是我尝试过的 .Net Core Web 应用程序中的示例 Razor 页面,适应你的需要):

@using Microsoft.AspNetCore.Html
@{
    bool isTrue = false;
}
<!DOCTYPE html>

<html>
<head>
    <title>title</title>
</head>
<body>
<div>
    <em>@(isTrue ? new HtmlString("hi") : new HtmlString("&nbsp;")) </em>
</div>
</body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 2011-06-06
    • 2015-04-22
    • 2020-03-14
    • 1970-01-01
    • 2018-07-02
    • 2015-05-21
    相关资源
    最近更新 更多