Search code examples
razor-2

Razor Conditional In Foreach


What's wrong this snippet?

I'm getting a "Text cannot appear within..." error

If you cut out the if statement the code's fine.

<ul>
@foreach(MenuItem item in @Model.MenuItems)
{
  String controller = item.Controller;
  String activeCss = "";

  if (item.IsActive)
  {
        activeCss = "active"
  }

  <li>
        @HTML.ActionLink()
  </li>

}
</ul>

Solution

  • Are you posting the actual code? There are several problems with the one you posted, but this should work:

    <ul>
    @foreach(MenuItem item in Model.MenuItems) // No need for @ before Model inside code.
    {
      String controller = item.Controller;
      String activeCss = "";
    
      if (item.IsActive)
      {
            activeCss = "active"; // Added ; here.
      }
    
      <li>
            @Html.ActionLink("Action", "Controller")
            // Html should not be upper-case, ActionLink requires arguments.
      </li>
    
    }
    </ul>