6

It's my first post, hence hello :)

I want to conditionally open and close div. What am I doing wrong?

@foreach (var m in Model.Recipes)
{
    if (left)
    {
        <div class="rec-line">
    }    

    if (left)
    {            
        </div>
    }
}
Mariusz.W
  • 1,347
  • 12
  • 19
  • Can you describe exactly what you are expecting to happen, and what is actually happening? – Mike Mooney Feb 03 '12 at 21:17
  • You can't open and close elements in different blocks like that. What are you trying to accomplish? There might be a better way to do what you are trying to do. – J. Holmes Feb 03 '12 at 21:25
  • It's solved below, but for your curiosity I am listing elements from the collection in pairs. Hence, on every odd element I open div and after even one I close it. [div] [left][right] [/div] [div]... – Mariusz.W Feb 03 '12 at 22:03

1 Answers1

6

You need to use the escape character to let the razor engine know that <div> is text by using @:

code:

@foreach (var m in Model.Recipes)
{
if (left)
{
    @:<div class="rec-line">
}    

if (left)
{            
    @:</div>
}
}
Travis J
  • 81,153
  • 41
  • 202
  • 273
  • No you don't: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx –  Feb 03 '12 at 21:35
  • 2
    @Shark - Yes you do. Re read your article "`@if (foo) { @:Plain Text is @bar }`". Clearly if you try to compile the op's original code it will have a logical error and display improperly. The fix to this situation is to add in the @: markers so that the html markup does not break the c# statements. To be clear, without @: this will not render, with @: this will render. – Travis J Feb 03 '12 at 21:38
  • Thank you. The problem was that between these ifs I have a lot of code (with js etc.) and I just couldn't figure out what should be escaped! Thanks! – Mariusz.W Feb 03 '12 at 21:58
  • Also just solved my problem trying to close off a row div every 4 items. – Iain M Norman Jul 19 '13 at 13:47