Question

How does one conditionally render an HTML element in Razor 2?

For instance, suppose I had the tag

    <div class="someclass">
         <p>@somevalue</p>
    </div>

And I wanted to suppress the <-div-> tag from rendering if the value of @somevalue was equal to 1. Is there a simple way to do this in Razor similar to how I might "hide" the <-div-> tag with Knockout.js in a browser, where I might :

    <div class="someclass" data-bind="showWhenTrue: someValue != 1">
         <p data-bind="text: someValue"></p>
    </div>

At the moment, the best Razor alternative I have is to do this:

      @if (someValue != 1) {
         <div class="someclass">
               <p>@somevalue</p>
         </div>
      }
Was it helpful?

Solution

There are many ways to do this. First, it should be noted that your knockout code doesn't actually remove the html from output, it just sets its display to hidden.

The razor code you have actually removes the code from the rendered HTML, so that's a very different thing.

To answer your question, we need to know what it is you're trying to achieve. If you just want to hide the display, you can simply do something like this:

<div class="someclass" style="display: @{ somevalue == 1 ? @:"none" : @:"block" };">
     <p>@somevalue</p>
</div>

You could also do it with a class:

<div class="someclass @{ somevalue == 1 ? @:"HideMe" : @:"ShowMe" }">
     <p>@somevalue</p>
</div>

If you want to remove the code from the output, then you can just do what you've done.. i'm mot sure what you find so objectionable about it... but if you want other alternatives, you could create an Html helper, you could use a razor helper, you could use a Display or EditorTemplate....

The list is actually quite long and i'm just scratching the surface...

OTHER TIPS

An elegant (and re-usable) solution is to write an extension method for Html to do conditional rendering of text ( a bit like IF() in Excel) - e.g.

   public static MvcHtmlString ConditionalRender(this HtmlHelper helper, bool condition, string trueString, string falseString = "")
   {
       return MvcHtmlString.Create((condition) ? trueString : falseString);
   }

You can then use it in your code as such:

   <div class="someclass" style="display: @Html.ConditionalRender(somevalue == 1, "none","block")">
        <p>@somevalue</p>
   </div>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top