Blazor: How to use the onchange event in <select> when using @bind also?

浪子不回头ぞ 提交于 2020-01-24 05:24:26

问题


I need to be able to run a function after a selection in made in a <select>. The issue is I'm also binding with @bind and I get a error when I try to use @onchange stating that it is already in use by the @bind. I tried using @onselectionchange, but that does nothing(doesn't run the function). I could forget the @bind and just assign @onchange to a function, but I'm not sure how to pass the selected value to the function.

I have the following code:

<select @bind="@SelectedCustID" @ @onchange="@CustChanged" class="form-control">
    @foreach (KeyGuidPair i in CustList)
    {
        <option value="@i.Value">@i.Text</option>
    }
</select>

Thanks.


回答1:


This seems to be a popular confusion. Firstly you cant use @onchange since it would internally be used by @bind. You should be able to access the selected value from the setter of your CustChanged property. Based on what you are trying to do with your CustChanged, you may not even need to manually check when this value is updated. For instance, if your intent is to use CustChanged in your UI directly or indirectly (within Linq or something), the UI would automatically update with CustChanged value when your <select> is changed. Hence, for most use cases I don't see the need to check when it was updated.

To use @onchange, you can bind it to a function something like this:

public void OnUpdated(ChangeEventArgs e)
{
    var selected = e.Value;
}



回答2:


<input @bind="MyProperty" />

@code  {
    private string myVar;

    public string MyProperty
    {
        get { return myVar; }
        set
        {
            myVar = value;
            SomeMethod();
        }
    }

    private void SomeMethod()
    {
        //Do something
    }
}


来源:https://stackoverflow.com/questions/58125929/blazor-how-to-use-the-onchange-event-in-select-when-using-bind-also

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