9

我在 else 块中显示(而不是显示)纯文本时遇到问题。

if (Model.CareerFields != null && ViewBag.CFCount > 0)
{
<h3>Careerfields Listing</h3>

<table>
   <tr>
      <th></th>
      <th>Careerfield Name</th>
   </tr>

   @foreach (var item in Model.CareerFields)
   {
       <tr>
       <td>
          @Html.ActionLink("Select", "Index", new { careerFieldID = item.CareerFieldId })
       </td>
       <td>
          @item.CareerFieldName
       </td>
       </tr>
   }
   </table>
}
else
{
  No Careerfields associated with @ViewBag.SelectedDivisionTitle
}

if 块工作正常。文本仅在 true 时呈现。但是,else 块文本会在页面加载时呈现,而不是仅在其评估为 false 时呈现。

我试过使用

Hmtl.Raw("No Careerfields associated with ")
<text>No Careerfields associated with @ViewBag.SelectedDivisionTitle</text>
@:No Careerfields associated with @ViewBag.SelectedDivisionTitle

但它仍然在评估之前呈现明文。

有什么建议么?

4

3 回答 3

11

将您的“纯文本”放在裸<span>标签中:

else
{
  <span>No Careerfields associated with @ViewBag.SelectedDivisionTitle</span>
}

浏览器不应该将它呈现为特殊的(除非你有 css 选择每个跨度),它会帮助剃刀感知 C# 的结尾并打印你的 HTML。

于 2012-08-01T21:21:19.147 回答
10

以下代码对我来说非常有效:

@if (false) {
    <h3>
        Careerfields Listing
    </h3>
    <table>
        <tr>
            <th>
            </th>
            <th>
                Careerfield Name
            </th>
        </tr>
    </table>
}
else 
{ 
    @:No Careerfields associated with @ViewBag.SelectedDivisionTitle
}

您可以看到,当您将条件更改为true时,会呈现if的内容。

于 2013-07-16T10:08:56.077 回答
2

看起来你忘记了陈述@前的标志。if尝试这个:

@if (Model.CareerFields != null && ViewBag.CFCount > 0)
{
    <h3>Careerfields Listing</h3>

    <table>
        <tr>
            <th></th>
            <th>Careerfield Name</th>
        </tr>

        @foreach (var item in Model.CareerFields)
        {
            <tr>
                <td>
                    @Html.ActionLink("Select", "Index", new { careerFieldID = item.CareerFieldId })
                </td>
                <td>@item.CareerFieldName</td>
            </tr>
        }
    </table>
}
else
{
    <text>No Careerfields associated with @ViewBag.SelectedDivisionTitle</text>
}
于 2012-11-02T10:31:32.103 回答