107

With RazorViewEngine, I can do this:

if (somecondition) {
     <div> some stuff </div>
}

but I can't seem to do this (Razor gets confused):

if (somecondition) {
    <div>
}

if (someothercondition) {
    </div>
}

I have a situation in which I need to put my opening and closing html tags in different code blocks - how can I do this in Razor?

sydneyos
  • 4,527
  • 6
  • 36
  • 53

4 Answers4

173

Try like this:

if (somecondition) {
    @:<div>
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
63

To explain Darin's answer, i.e prefixing the HTML like this:

@:<html>

@: in Razor means 'render something as plain text'

or you can use this, which outputs the HTML as you orginally wrote it (this can also be used to avoid the automatic HTML encoding that Razor does if you're trying to output HTML):

@Html.Raw("<html>")

(Html.Raw reference from MS - http://msdn.microsoft.com/en-us/library/gg568896(v=vs.111).aspx)

Chris Halcrow
  • 28,994
  • 18
  • 176
  • 206
4

You can create a custom MVC Helper method. For with you create a public static class MyRenderHelpers in namespace System.Web.Mvc.Html and write a method Html.

namespace System.Web.Mvc.Html
{
    public static class MyRenderHelpers
    {
        public static MvcHtmlString Html(this HtmlHelper helper, string html, bool condition)
        {
            if (condition)
                return MvcHtmlString.Create(html);
            else
                return MvcHtmlString.Empty;
        }
    }
}

Now you can use this extension method in your razor view:

@Html.Html("<div>", somecondition)
Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
3

The fact that you have to do this usually indicates that your view code is not factored correctly. The nature of HTML is to have balanced or self-enclosed tags (at least in HTML 4, HTML 5 seems to be leaning away from it) and Razor depends on that assumption. If your going to conditionally ouptut a <div> then you will also somewhere later output </div>. Just put the whoel pair in your if statement:

@if(something) {
    <div>
        Other stuff
    </div>
}

Otherwise you end up with weird code like here.

Community
  • 1
  • 1
marcind
  • 52,944
  • 13
  • 125
  • 111
  • 7
    My situation is that I want to – sydneyos Jan 27 '11 at 00:10
  • Right, my point is that in 99% cases you probably shouldn't. But you might fit into that 1% in which case there's `@:` or `` – marcind Jan 27 '11 at 00:47
  • 7
    he probably has a closing block later : `if (somecondition) { @: }` – Simon_Weaver Jan 28 '11 at 02:58
  • yes, he has to. my point is that such views can be refactored so that such dual conditionals are not necessary. – marcind Jan 28 '11 at 03:55
  • Not easily for this scenario `@if(true) { }` – Michiel van Oosterhout Sep 01 '11 at 16:48
  • @michielvoo in this case you should close the tag: `@if(true) { }` – marcind Sep 01 '11 at 17:31
  • 1
    @michielvoo Why is it bad to use this method to have a conditional div wrapper for example? Also in HTML5 you do not close `` tags. – Chris Haines Jun 20 '13 at 09:44
  • If you need to have html tags conditionally wrapping certain frame depths during a recursive method as it unwinds, I think you need to be able to do this - at least I haven't figured out another way. – Timothy Lee Russell Apr 30 '14 at 20:11
  • Late comment, but since it has a vote and is therefore showing: "Also in HTML5 you do not close tags." Actually, in 8.1.2.1 #6 of https://www.w3.org/TR/2011/WD-html5-20110113/syntax.html#elements-0 it states that "Then, if the element is one of the void elements, or if the element is a foreign element, then there may be a single U+002F SOLIDUS character (/)." Void elements, as noted in 8.1.2 Elements, include `link`. So you don't have to close them, but you can, as long as you do so in the start tag. – James Skemp Oct 29 '19 at 14:09
  • 1
    Surely there are circumstances where what is desired is legitimate. You might want to bold certain stuff conditionally - where the "stuff" is included either way, but the start and end bold tags are conditional. As long as it's the same condition, that should be fine, surely – richjhart Apr 07 '20 at 17:17
  • So how do I create a table of images, say 2 images wide, out of an array of images ? A. foreach loop with a counter and when (counter %2 == 0) close the row and start a new row. And if you're using a table razor compiler complains because there is no '' tag before the tag. – Duncan Groenewald Sep 09 '20 at 03:22
  • @marcind: I had to do two different views because, I tried hard to do a conditional generation of the initial `
    `s block and the final `
    `s block, but I always got errors or things not working. In PHP, I could easily do this without duplication. So after all this contributes to worse code factoring.
    – sergiol Jul 03 '23 at 12:01