Question

I'm trying to run a while loop that keeps going through a list until the entry is null. My code looks like so:

int i = 0;

while(list[i] != null)
{

    <dl class="dl-horizontal">
        <dt>
            list[i].Name
        </dt>

        <dd>
            list[i].Damage
        </dd>
    </dl>
    i++;
}

The error I'm getting is that i doesn't exist in the context of the while loop. I can't define it inside of the loop because then it will be reset to 0 on each pass through yet I'm not sure what else to do.

Was it helpful?

Solution 2

When you insert HTML elements into your Razor file, it escapes out of C# mode, so you need to add the @ sign to your variable calls.

EDIT: You also need the @ sign on the while and declaration statements:

@{ int i = 0; }

@while(list[i] != null)
{
  <dl class="dl-horizontal">
      <dt>
          @list[i].Name 
      </dt>

      <dd>
          @list[i].Damage
      </dd>
  </dl>
  i++;
}

This will put you back into the C# context and evaluate the expression.

OTHER TIPS

Try declaring your variable inside the code block at the top of your page:

@{
    int i = 0;
}

Then :

@while(list[i] != null)
{

    <dl class="dl-horizontal">
        <dt>
            @list[i].Name
        </dt>

        <dd>
            @list[i].Damage
        </dd>
    </dl>
    i++;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top