user70192
user70192

Reputation: 14214

Unable to render HTML conditionally with Razor in ASP.NET MVC

I'm working on an ASP.NET MVC app that uses Razor. Part of the HTML is rendered via a loop. I need to conditionally create an opening/closing element. For some reason, the view renderer throws a runtime error when i try the following:

  <div id="content">
    <div id="banner">@ViewBag.BannerText</div></br>

    <div id="group">
@{ 
  int currentID = 0;
  foreach (Item item in ViewBag.Items) {
  if (currentID != item.ID) {
      <div>
        <h3>@item.GetItemTitle()</h3>    
        <div>@item.Name</div>
  }

  if (currentID != item.ID) {
    @Html.Raw("</div>");
    currentID = item.ID;   
  }
}
</div>
</div>

Everything looks correct to me. However, I can't figure out why it won't work. It seems like everytime I had the @Html.Raw("") it fails. However, if I remove the conditional if-statement and the @Html.Raw(""); it works fine.

Upvotes: 0

Views: 1652

Answers (1)

Chad Campbell
Chad Campbell

Reputation: 129

The problem is your closing DIV must be in the same block as the opening DIV. Use @Html.Raw on your opening DIV and your problem should go away.

Upvotes: 1

Related Questions