Calling function from generated button in Blazor

独自空忆成欢 提交于 2019-12-23 22:58:13

问题


I'm currently trying to call a method from some autogenerated buttons, that are set up from some configuration. So the number of buttons is configurable. I have the blazor page as shown below. My problem is that if I have 3 buttons and I press one then ButtonClicked is called correctly, but the index is always 3 - the end value of int i for the for-statement. I of course want the index of the button to be passed to the function. One obvious solution would be to wrap a button in my own component that would then take an index-parameter and this could be passed along to a buttonclicked event, but how can I make the code below work without making my own button component?

@inject Navigator navigator

<div class="chooseDiv">
    @for (int i = 0; i < Buttons.Count; i++)
    {
        <button type="button" class="btn btn-primary btn-lg" style="margin:10px" onclick="@((ui) => ButtonClicked(i))">@Buttons[i]</button>
    }
</div>

@functions {
    [Parameter] List<string> Buttons { get; set; } = new List<string>() { "You forgot to declare your buttons" };

    private void ButtonClicked(int index)
    {
        Console.WriteLine("Button clicked with index:" + index);
        navigator.CurrentResult = index;
        navigator.Next();
    }
}

回答1:


I guess you should add a local variable to your loop as follows:

@for (int i = 0; i < Buttons.Count; i++)
    {
        var local = i;
        <button type="button" class="btn btn-primary btn-lg" style="margin:10px" onclick="@((ui) => ButtonClicked(local))">@Buttons[i]</button>
    }

This is a standard C# behavior, not related to Blazor, where the lambda expression @((ui) => ButtonClicked(i)) has access to a variable and not to its value. You've got to define a variable which is local to your loop, otherwise your lambda expression always calls ButtonClicked(i) and i equals 3 when the loop ends.

Hope this helps...



来源:https://stackoverflow.com/questions/55278600/calling-function-from-generated-button-in-blazor

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