如何用Razor显示条件纯文本

时间:2012-08-01 21:17:49

标签: asp.net-mvc-3 razor

我遇到了在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块工作正常。文本仅在呈现时呈现。但是,else块文本在页面加载时呈现,而不是仅在其计算结果为false时呈现。

我尝试过使用

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

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

有什么建议吗?

3 个答案:

答案 0 :(得分:8)

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

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

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

答案 1 :(得分:7)

以下代码对我来说非常合适:

@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 的内容。

答案 2 :(得分: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>
}