19

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?

4

3 回答 3

39

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++;
}
于 2013-08-23T15:56:15.100 回答
15

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

于 2013-08-23T15:57:18.587 回答
11

You can also use:

if(condition){
 @:<div>
}

if(condition){
 @:</div>
}
于 2016-03-01T15:36:42.433 回答