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.
To retrieve a selected value from the select control, you can use either the @bind or @onchange event.
Bind to a Model To bind the DropDownList to a model: Populate its Data parameter with the collection of items you want in the dropdown. Set the TextField and ValueField parameters to point to the corresponding property names of the model. Set the Value property to the intial value of the component (optional).
Bind a property or field on other Document Object Model (DOM) events by including an @bind:event="{EVENT}" attribute with a DOM event for the {EVENT} placeholder. The following example binds the InputValue property to the <input> element's value when the element's oninput event ( input ) is triggered.
In Blazor, there is no significant difference between using these two attributes. The @bind attribute is a shorthand of the @bind-value attribute and its delegate will trigger the ValueChanged event of the component.
<select @bind="MyProperty"> <option>Your Option<option> </select> @code { private string myVar; public string MyProperty { get { return myVar; } set { myVar = value; SomeMethod(); } } private void SomeMethod() { //Do something } }
@bind
is essentially equivalent to the having both value
and @onchange
, e.g.:
<input @bind="CurrentValue" />
Is equivalent to:
<input value="@CurrentValue" @onchange="@((ChangeEventArgs e) => CurrentValue = e.Value.ToString())" />
Since you've already defined @onchange
, instead of also adding @bind
, just add value
to prevent the clash:
<select value="@SelectedCustID" @onchange="@CustChanged" class="form-control"> @foreach (KeyGuidPair i in CustList) { <option value="@i.Value">@i.Text</option> } </select>
Source: https://docs.microsoft.com/en-us/aspnet/core/blazor/components/data-binding?view=aspnetcore-3.1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With