Search code examples
htmlrazorhtml-helperrazor-2

Razor generating ragged html does it require Html.Raw?


Given a dynamic grid model generating html via razor similar to:

@{ int blockCounter = 0;}

@foreach (var item in Model.Items)
{
    if (blockCounter++ % 3 == 0)
    {
    //ragged html open here, when needed
    }

    <div>..... </div>

    if (blockCounter % 3 == 0)
    {
    //ragged html close, when needed
    }

}

Is there any alternative to

if (blockCounter++ % 3 == 0)
{
@Html.Raw(@"<div class=""row"">")
}

If the following code is used:

if (blockCounter++ % 3 == 0)
{
    <div class="row">
}

This results in Parser Error Parser Error Message: The foreach block is missing a closing "}" character. Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup.

This parser error is false, as commenting out the ragged html or inserting it into a raw block removes the error. Is the raw block the only solution to this?


Solution

  • You should be able to use @: to output text for single lines within a code block or the <text> tag for multiple lines

    // single line
    if (blockCounter++ % 3 == 0)
    {
        @:<div class="row">
    }
    
    // multiline
    if (blockCounter++ % 3 == 0)
    {
        <text>
            <div class="row">
            <span>more output</span>
        </text>
    }
    

    Additional syntax references can be found here... http://www.asp.net/web-pages/overview/getting-started/introducing-razor-syntax-(c)