Nezir
Nezir

Reputation: 6915

MVC If statement in View

I have problem with IF statement inside MVC View. I am trying to use it for creating row for every three items.

<div class="content">
  <div class="container">
    @if (ViewBag.Articles != null)
    {
      int nmb = 0;
      foreach (var item in ViewBag.Articles)
      {
        if (nmb % 3 == 0) { 
          <div class="row">  
        }    
        <a href="@Url.Action("Article", "Programming", new { id = item.id })">    
          <div class="tasks">    
            <div class="col-md-4">    
              <div class="task important">
                <h4>@item.Title</h4>
                <div class="tmeta">
                  <i class="icon-calendar"></i> @item.DateAdded - Pregleda:@item.Click  
                  <i class="icon-pushpin"></i> Authorrr  
                </div>    
              </div>    
            </div>
          </div>
        </a>
        if (nmb % 3 == 0) { 
          </div>
        }
      }
    }
  </div>
</div>

Upvotes: 33

Views: 153726

Answers (2)

John H
John H

Reputation: 14655

You only need to prefix an if statement with @ if you're not already inside a razor code block.

Edit: You have a couple of things wrong with your code right now.

You're declaring nmb, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:

@if (ViewBag.Articles != null)
{
    int nmb = 0;
    foreach (var item in ViewBag.Articles)
    {
        if (nmb % 3 == 0)
        {
            @:<div class="row"> 
        }

        <a href="@Url.Action("Article", "Programming", new { id = item.id })">
            <div class="tasks">
                <div class="col-md-4">
                    <div class="task important">
                        <h4>@item.Title</h4>
                        <div class="tmeta">
                            <i class="icon-calendar"></i>
                                @item.DateAdded - Pregleda:@item.Click
                            <i class="icon-pushpin"></i> Authorrr
                        </div>
                    </div>
                </div>
            </div>
        </a>
        if (nmb % 3 == 0)
        {
            @:</div>
        }
    }
}

The important part here is the @:. It's a short-hand of <text></text>, which is used to force the razor engine to render text.

One other thing, the HTML standard specifies that a tags can only contain inline elements, and right now, you're putting a div, which is a block-level element, inside an a.

Upvotes: 57

Bogdan Balas
Bogdan Balas

Reputation: 355

Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....

Upvotes: 2

Related Questions