Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC/Razor : Conditional nested html tag

Tags:

I'd like to have this html code where a condition ("myBool") is true :

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

and this one when it's false :

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

I dont what to whave to write se same code ("other stuffs") twice so I tried this :

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

but I get compilation errors.

Do you see how I could do what I want without having to do somethig like that :

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

Thank you.

like image 650
Sharpac Avatar asked Feb 14 '13 16:02

Sharpac


1 Answers

The following might work using the @: operator. When you're inside a code block, either because of a control structure (like in the example given below) or because you have explicitly defined one, you can output plain text by prefixing with a @-character followed by a : (colon) character.

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

    @sometext

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

    ... other stuffs

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

or you might also try the following:

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

    ... other stuffs  

    @if (someCondition)
    {
        @:</fieldset>
    }  
</div>
like image 131
Darin Dimitrov Avatar answered Nov 09 '22 22:11

Darin Dimitrov