Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 Razor If splitting div tags

I have the following MVC 4 Razor code:

@for (int i = 1; i <= 100; i++) {

    if (currentCol == 1) {
        Html.Raw("<div class=row>");
    @*Need to do this because can't have a open div within a if compiler doesnt like it *@
    } if (currentCol == maxCol) {
        Html.Raw("</div>");
    }
    currentCol++;
}

I am basically trying to generate the contents of every div class row conditionally with the start and end tags in different paths of the if statements. When I just use straight HTML, the compiler doesn't like it and thinks the brackets are off. It seems like Html.Raw is the solution from my searches online, but when I use Html.Raw, the div doesn't show up when I view the source.

Does anyone know what's going on?

like image 816
user2129585 Avatar asked Aug 23 '13 15:08

user2129585


3 Answers

Try prefixing the Html.Raw calls with @:

@for (int i = 1; i <= 100; i++) 
{
    if (currentCol == 1) 
    {
        @Html.Raw("<div class=row>");
    } 
    if (currentCol == maxCol) 
    {
        @Html.Raw("</div>");
    }
    currentCol++;
}
like image 149
Darin Dimitrov Avatar answered Oct 14 '22 10:10

Darin Dimitrov


Razor follows HTML and C#/VB syntax blocks, which is why breaking up tags does this. Two work-arounds:

1: Use Html.Raw (as you've done)

if (condition){
  @Html.Raw(@"<div class=""row"">")
}else{
  @Html.Raw("</div>")
}

2: Use the Special <text>...</text> tags.

if (condition){
  <text>
    <div class="row">
  </text>
}else{
  <text>
    </div>
  </text>
}

Remember that the @ symbol, to the Razor parser, means you're making a transition from one language to the other (albeit HTML to code, or vice versa). So, since you're in an if(...) block and Html.Raw is actually outputting HTML, you need to use the @.

like image 27
Brad Christie Avatar answered Oct 14 '22 10:10

Brad Christie


You can also use:

if(condition){
 @:<div>
}

if(condition){
 @:</div>
}
like image 30
Konrad Avatar answered Oct 14 '22 10:10

Konrad