Blazor onclick 事件从循环传入计数器 [英] Blazor onclick event passing in counter from loop

查看:31
本文介绍了Blazor onclick 事件从循环传入计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在通过 Blazor 中的本地解决方案实现表格分页,但遇到了一些困难.麻烦的代码如下(这是为了在网格下方呈现分页按钮):

I'm currently implementing table paging via a home grown solution in Blazor and coming across some difficulty. The troublesome piece of code is below (this is for rendering the paging buttons below a grid):

@for (int i = 0; i < vm.TotalPages; i++)
{
    <button id="pg-button-@i" class="btn btn-primary btn-sm" type="button" onclick="@(() => GetTablePage(i))">@i</button>
}

注意在 onclick 事件中,我正在调用一个函数并传入 i,这是循环当前交互的计数器.

Notice in the onclick event, I am calling a function and passing in i, the counter for the current interation of the loop.

GetTablePage 方法如下所示:

protected async Task GetTablePage(int page)
{
    Console.WriteLine("page number: " + page);
}

我的问题是每个按钮都会调用这个函数,i 设置为 vm.TotalPages 的长度.

My issue is that EVERY button will call this function with i set as the length of vm.TotalPages.

这里有一个例子试图让这更清楚:

Here is an example to try to make this more clear:

查看标记(注意每个按钮的 id 设置适当):

View Markup (notice the id of each button is set appropriately):

<button id="pg-button-0" class="btn btn-primary btn-sm" type="button">0</button>
<button id="pg-button-1" class="btn btn-primary btn-sm" type="button">1</button>
<button id="pg-button-2" class="btn btn-primary btn-sm" type="button">2</button>
<button id="pg-button-3" class="btn btn-primary btn-sm" type="button">3</button>
<button id="pg-button-4" class="btn btn-primary btn-sm" type="button">4</button>
<button id="pg-button-5" class="btn btn-primary btn-sm" type="button">5</button>
<button id="pg-button-6" class="btn btn-primary btn-sm" type="button">6</button>

在单击这些按钮中的任何一个时,我的 GetTablePage 函数正在将 7 写入控制台,这是 vm.TotalPages 集合的长度.

Upon clicking ANY of these buttons, my GetTablePage function is writing 7 to the console which is the length of the vm.TotalPages collection.

为什么会发生这种情况,我该如何克服?

Why is this happening and how can I overcome it?

推荐答案

因为 i 是一个变量,for 循环总是在你点击的时候结束,那一刻是 7

Because i is a variable and the for loop is always finished when you click, it is 7 on that moment

您需要执行以下操作:

@for (int i = 0; i < vm.TotalPages; i++)
{
    var tempint = i;
    <button id="pg-button-@i" class="btn btn-primary btn-sm" type="button" onclick="@(() => GetTablePage(tempint))">@i</button>
}

这篇关于Blazor onclick 事件从循环传入计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆