Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 959
Daprin Wakaliana Avatar asked Apr 07 '16 04:04

Daprin Wakaliana


1 Answers

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

like image 178
Ali Gh Avatar answered Sep 29 '22 04:09

Ali Gh