Get Select2 Selected Value From Code Behind ASP .Net Web Form
Asked Answered
E

1

6

I have a problem with Select2 V 4.02

Here is my code

<select id="MySelect" class="form-control" runat="server" ClientIDMode="static">
    <option></option>
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
</select>
<asp:Button Text="Show Select2 Result" runat="server" ID="btnShow" OnClick="btnShow_Click"/>

jQuery:

$('#MySelect').select2({
        placeholder: "-Select-"
});

My question is: Can I get the "MySelect" selected value from ASP .Net Code behind? I tried this code from code behind asp .net webform

protected void btnShow_Click(object sender, EventArgs e)
{
    Response.Write(MySelect.Value);
}

But it returns empty string.

Economically answered 7/4, 2016 at 4:57 Comment(8)
It must have returned the first value, which is empty. Have you tried selecting A, B or C and checked in code-behind?Tonsillectomy
Yes, I have tried It. It still shows empty string as result. I have debugged it and add watch "MySelect", but there are no properties that shows the selected valueEconomically
Which event is triggered in code-behind where you checked MySelect.Value?Tonsillectomy
I will edit my questiong to make it clearEconomically
Is that what you mean? @BikashSinghMaharjanEconomically
Okay. I just did a quick test in fresh Webform. It seems to be fine. I can get the selected value in button click event of code-behind. That's why i need to know more in order to solve this case. Check out imgur.com/XMa4k9JTonsillectomy
Why are you using select and not DropDownList?Akbar
By the way I am using this library for Select2: select2.github.io/examples.htmlEconomically
S
7

you can use standard hidden field like this :

<asp:HiddenField ID="hf1" runat="server" />

then in your JavaScript :

$('#MySelect').on('change', function () {
   $('#<%=hf1.ClientID%>').val($(this).val());
}

in your code behind :

protected void btnShow_Click(object sender, EventArgs e)
{
    Response.Write(hf1.Value);
}

i hope work for you

Slagle answered 12/5, 2016 at 9:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.