html - MVC/ Razor : Conditional nested html tag

标签 html asp.net-mvc razor

我想要一个条件(“myBool”)为真的 html 代码:

<div>
  <fieldset>
    <legend>
      @sometext
    </legend>
    ... other stuffs
  </fieldset>
<div>

这个是假的:

<div>
  <b>
    @sometext
  </b>
  ... other stuffs
<div>

我不知道要写两次相同的代码(“其他东西”),所以我尝试了这个:

<div>
@if(myBool)
{
  <fieldset>
    <legend>
}
else
{
  <b>
}
@sometext
if (myBool)
{
  </legend>
}
else
{
  </b>
}
...other stuff
if (myBool)
{
  </fieldset>
}
</div>

但是我得到了编译错误。

你知道我如何可以做我想做的事而不必做那样的事情吗:

@if(myBool)
{
  <div>
    <fieldset>
      <legend>
        @sometext
      </legend>
      ... other stuffs
    </fieldset>
  <div>
}
else
{
  <div>
    <b>
      @sometext
    </b>
    ... other stuffs
  <div>
}

谢谢。

最佳答案

以下可能会使用 @: 运算符。 当您在代码块内时,无论是因为控制结构(如下面给出的示例)还是因为您已经明确定义了一个代码块,您都可以输出纯文本,方法是在 @ 字符前加上 :(冒号)性格。

<div>
    @if (someCondition)
    {
        @:<fieldset>
            @:<legend>
    }
    else
    {
        @:<b>
    }

    @sometext

    if (someCondition)
    {
        @:</legend>
    }
    else
    {
        @:</b>
    }

    ... other stuffs

    @if (someCondition)
    {
        @:</fieldset>
    }
</div>

或者您也可以尝试以下操作:

<div>
    @Html.Raw(someCondition ? "<fieldset><legend>" : "<b>")
    @sometext
    @Html.Raw(someCondition ? "</legend>" : "</b>")

    ... other stuffs  

    @if (someCondition)
    {
        @:</fieldset>
    }  
</div>

关于html - MVC/ Razor : Conditional nested html tag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14879864/

相关文章:

php - WordPress 侧面板

c# - 从 View POST 时列表为 NULL

asp.net-mvc - 如何从 MVC 页面引用 Razor 页面部分 View ?

c# - Razor 无法检测到部分结束

javascript - 如何判断用户点击的是视频元素还是视频控件之一?

javascript - 如何有多个下拉菜单

php - 用PHP搜索MySQL并在同一页面显示结果

c# - MVC 下拉列表的动态内容变化

vb.net - 我可以在 @Using.BegingForm() 中渲染 @Section 吗?

asp.net-mvc-3 - MVC3 razor View 错误 Microsoft JScript 运行时错误 : Object doesn't support property or method 'datepicker' `