TMC
TMC

Reputation: 8154

Razor syntax: Trouble figuring out nested statements and variable scope

I'm having trouble figuring out Razor syntax and how variable scope works. I'm new to C# in general as well as Razor syntax. Here is some code I created parallel what I'm looking to do, just a bit simpler.

I have an array represented by ViewBag.Photos that I want to iterate though to display in my UI code. However, for the first photo, I need to add a distinctive secondary class named active for my UI code (using a jquery plugin) to display properly since it needs to know what the first photo is.

What am I doing wrong and what is the best way to accomplish it?

<div class="foo">
    @{int i = 1;}
    @foreach (var photo in ViewBag.Photos) 
    {
        if (i == 1) { 
            <div class="item active">
        } 
        else {
            <div class="item">
        }
        <img src="@photo" alt="@ViewBag.SomeVar">
        <div class="bar">
            <p>Test</p>
        </div>
        </div>
        @{i++};
    }
</div>

Upvotes: 3

Views: 3653

Answers (2)

Yorgo
Yorgo

Reputation: 2678

<div class="foo">
    @{
          int i = 1;
          @foreach (var photo in ViewBag.Photos) 
          {
             if (i++ == 1) { 
               <div class="item active">
             } 
             else {
               < div class="item">
             }
             <img src="@photo" alt="@ViewBag.SomeVar">
             <div class="bar">
                <p>Test</p>
             </div>
             </div>

       }
    }
</div>

or

    <div class="foo">
    @{
          int i = 1;
          var className = "item";
          @foreach (var photo in ViewBag.Photos) 
          {
             className = i++ == 1 ? "item active" : "item";
             <div class="@className">
                   <img src="@photo" alt="@ViewBag.SomeVar">
                   <div class="bar">
                       <p>Test</p>
                  </div>
             </div>

       }
    }
</div>

Upvotes: 2

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93444

You should use a for statement, rather than a foreach.

<div class="foo"> 
@for(int i = 0; i < ViewBag.Photos.Count; i++)  
{ 
    <div class="@((i == 0) ? "item active" : "item")">
        <img src="@ViewBag.Photos[i].Photo" alt="@ViewBag.Photos[i].AltText"> 
        <div class="bar"> 
            <p>Test</p> 
        </div> 
    </div> 
} 
</div> 

I assume Photos is an array of some class that wraps both the photo and alt text. If not, you would do something like this:

<img src="@ViewBag.Photos[i]" alt="@ViewBag.AltText[i]"> 

You really should be using a View Model, however. You would probably also do better using a DisplayTemplate as well. But that should get you started.

UPDATE: I would write the code as the above using the conditional operator. I think it's easier to read, and less confusing.

Upvotes: 1

Related Questions