For loop not returning expected value - C# - Blazor

后端 未结 1 2083
忘掉有多难
忘掉有多难 2020-12-12 01:43

Using Blazor, I am creating a pagination feature for my project. The main concept is just using linq\'s .Skip() and .Take(), I will only take the list items for the page cli

相关标签:
1条回答
  • 2020-12-12 01:55

    Your for loop should contain a local variable like this:

     @for (int i = 0; i < Math.Ceiling((decimal)articleService.ReturnAll().Count() / numPerPage); i++)
        {
           var localVariable = i;
    
          <li class="page-item"><a class="page-link" onclick="@(() => ReturnPage(localVariable ))">@i</a></li>
        }
    

    This is standard C# behavior where lambda expression @(() => ReturnPage(localVariable )) has access to a variable and not to the value of the variable. You have to define a variable which is local to the for loop, otherwise your lambda expression will always call ReturnPage(i) and i equals Math.Ceiling((decimal)articleService.ReturnAll().Count() at the end of the loop.

    0 讨论(0)
提交回复
热议问题