Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor if / else inside a for loop: The for block is missing a closing "}" character

I am doing a simple for loop in Razor syntax in MVC:

@for (int i = 0; i < Model.ProductViewModels.Count; i++)
{
    if (i%2 == 0)
    {
        <div class="row">
    }
        <div class="col-md-4">
      <a href="/[email protected][i].Id">@Model.ProductViewModels[i].Title - @Model.ProductViewModels[i].Isbn13
                <br />
                <img src="@Model.ProductViewModels[i].ImageUrl" />
            </a>
</div>

@if (i%2 == 0)
    {
        </div>
    }
}

This seems like pretty legal code in my mine mind, but it isn't working!

I get the error:

Meddelelse om parserfejl: The for 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.

Screenshot of error:

enter image description here

Any ideas? :) Thanks

like image 275
Lars Holdgaard Avatar asked Jan 28 '14 18:01

Lars Holdgaard


4 Answers

This solution work for me:

`

@foreach (var item in Model.listItems)
{
     if (item.isValid){
            @:<div class="validClass">
     }else{
            @:<div class="invalidClass">
     }
     @:</div>
}

`

You can try other solution as:

<div class="@if(item.isValid){WriteLiteral("validClass");}" ></div>

like image 98
Jorge Santos Neill Avatar answered Nov 14 '22 21:11

Jorge Santos Neill


This is a working solution, I tested in Visual Studio on a Razor View. You have to use @: properly.

  @for (int i = 0; i < Model.ProductViewModels.Count; i++)
  {            
       if (i % 2 == 0)
       {
           @:<div class="row">
       }

       <div class="col-md-4">
          <a href="/[email protected][i].Id">@Model.ProductViewModels[i].Title - @Model.ProductViewModels[i].Isbn13
          <br />
          <img src="@Model.ProductViewModels[i].ImageUrl" />
          </a>
       </div>

       if (i % 2 == 0)
       {
            @:</div>
       }            
   }
like image 34
ramiramilu Avatar answered Nov 14 '22 23:11

ramiramilu


you need to use text tags

if (i%2 == 0)
{
    <text>
        <div class="row">
    </text>
}

here is a link with more information http://weblogs.asp.net/scottgu/archive/2010/12/15/asp-net-mvc-3-razor-s-and-lt-text-gt-syntax.aspx

like image 3
Matt Bodily Avatar answered Nov 14 '22 22:11

Matt Bodily


Try this way:

if (i%2 == 0)
{
    @:<div class="row">
}

Or:

if (i%2 == 0)
{
    <text>
        <div class="row">
    </text>
}

Read this article

like image 1
karaxuna Avatar answered Nov 14 '22 23:11

karaxuna