Dynamic method parameter using Blazor Binding [duplicate]

和自甴很熟 提交于 2020-01-05 04:08:09

问题


I'm trying to make a paging component by using Blazor. Navigate First, Last, Previous and Next are already working. The problem is: I want the user to be able to click on a page number and the NavigateToPage action to be executed by passing the page number.

Here's my attempt:

<div class="col-12 col-md-6 col-lg-3 offset-lg-6 text-right">
    <nav aria-label="Page navigation example">
        <ul class="pagination justify-content-end">
            <li class="page-item @PuedeNavegarPrimeraPagina">
                <a class="page-link" tabindex="-1" @onclick="NavegarHaciaPrimeraPagina">Primera</a>
            </li>
            <li class="page-item @PuedeNavegarPaginaAnterior">
                <a class="page-link" tabindex="-1" @onclick="NavegarHaciaPaginaAnterior">Anterior</a>
            </li>
            @for (int i = 1; i <= TotalPaginas; i++)
            {
                var clasePaginacionPaginaActual = (PaginaActual == i) ? "disabled" : "";
                <li class="page-item @clasePaginacionPaginaActual"><a class="page-link" @onclick="(() => NavigateToPage(i))">@i</a></li>
            }
            <li class="page-item  @PuedeNavegarPaginaSiguiente">
                <a class="page-link" @onclick="NavegarHaciaPaginaSiguiente">Siguiente</a>
            </li>
            <li class="page-item  @PuedeNavegarUltimaPagina">
                <a class="page-link" @onclick="NavegarHaciaUltimaPagina">Última</a>
            </li>
        </ul>
    </nav>
</div>

The NavigateToPage expect the page number, but the current code always sends the same value for all links, which corresponds to the last value of i. If there are 4 pages, then 5 is the parameter no matter which of the links is clicked.

Any idea of how to get different parameters values?


回答1:


Your for loop should contain a local variable like this::

@for (int i = 1; i <= TotalPaginas; i++)
            {
                var local = i;
                var clasePaginacionPaginaActual = (PaginaActual == local) ? "disabled" : "";
                <li class="page-item @clasePaginacionPaginaActual"><a class="page-link" @onclick="@(() => NavigateToPage(local))">@i</a></li>
            }

This is standard C# behavior where lambda expression @(() => NavigateToPage(local)) 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 NavigateToPage(i) and i is 5 at the end of the loop.



来源:https://stackoverflow.com/questions/59461137/dynamic-method-parameter-using-blazor-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!