문제

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.

도움이 되었습니까?

해결책 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.

다른 팁

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++;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top