MVC 4 Razor If splitting div tags

2019-04-19 12:50发布

问题:

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?

回答1:

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++;
}


回答2:

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 @.



回答3:

You can also use:

if(condition){
 @:<div>
}

if(condition){
 @:</div>
}