20

条件 ("myBool") が true であるこの html コードが必要です。

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

false の場合は次のようになります。

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

同じコード(「その他のもの」)を2回書く必要がないので、これを試しました:

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

ありがとうございました。

4

1 に答える 1

40

以下は、@:演算子を使用して機能する可能性があります。制御構造 (以下の例のように) または明示的に定義したため、コード ブロック内にいる場合は、@ 文字の前に : (コロン) を付けることで、プレーン テキストを出力できます。キャラクター。

<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>
于 2013-02-14T17:22:58.293 に答える