Hello,
I'm trying to use a Select2 dropdown inside an EditForm but I'm not able to retrieve the selected data.
I have tried everything: @onchange, @bind, @bind-value, InputSelect instead of select and even initialize the component from javascript... nothing worked.
I've searched online for solution and I've already read the posts on this support... but again, nothing worked.
Is there a proved-working way to get the selected value from the Select2 component in Blazor?
Hi Christian,
Thank you for reaching out to us.
Can you try the example below?
<select @onchange="onChange" class="form-select" data-control="select2" data-placeholder="Select an option">
<option></option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
@code {
private string value { get; set; }
private void onChange(ChangeEventArgs e){
value = e.Value.ToString();
}
}
<select @bind="@value" class="form-select" data-control="select2" data-placeholder="Select an option">
<option></option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
Hi and thanks for the reply.
I tried both your pieces of code and they doesn't work.
What I mean with "it doesn't work" is that the selection of the component is actually working: if I click on option 2, the option 2 will be displayed... but if I try to get the value of the variable "value", it will always be null or String.Empty.
That's what I'm struggling to achieve and it's a fundamental logic for all the form in Asp.net Blazor framework.
Hi Christian,
I apologize for the inconvenience.
After checking this further it seems like for select2 inputs this should be done differently.
In your js code you can add the following global functions to get and set selec2 value.
getSelectedValues: function (elementId) {
return $("#" + elementId).val();
},
setSelectedValues: function (elementId, values) {
$("#" + elementId).val(values).trigger("change");
}
Hi Lauris and thanks for the reply.
Following the thread that you linked brought me to solution.
Thank you very much for the assistance!
Hi Christian,
Glad to hear that. All the best with your project!
Please don't hesitate to reach out if you need anything more from us.
Regards,
Lauris Stepanovs,
Keenthemes Support Team