4

I have code below:

 <select id="test">
        <option value="a">aaa</option>
        <option value="b">bbb</option>
    </select>
    <asp:Button ID="btnTest" runat="server" Text="Test it!" onclick="btnTest_Click" />

I need to get selected index not selected value on postback. How can I do this with asp.net? this is my code for filling the select html:

<script language="javascript" type="text/javascript">
    $(document).ready(function() {
    $("#<%=btnTest.ClientID %>").click(function(){
    $.ajax(
    { url: "StateCity.asmx/ReferItems?id=" + getParameterByName('id'),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        type: "POST",
        success: function(data) {
        $("#test").empty();
        $.each(data.d, function() {
        $("#test").append($("<option></option>").val(this['Value']).html(this['Text']));
        });

        },
        error: function() { alert("Error"); }
    }) 
    })
</script>
uzay95
  • 16,052
  • 31
  • 116
  • 182
Raymond Morphy
  • 2,464
  • 9
  • 51
  • 93

2 Answers2

5
  1. Add runat="server" attribute to the <select>
  2. In code behind (button handler code) do:
int selectedIndex = (test as HtmlSelect).SelectedIndex;

EDIT: Answer to comment regarding -1 value of the SelectedIndex property

MSDN HtmlSelect.SelectedIndex Property:

It is possible to have no item selected. If no item is selected, the SelectedIndex property contains a value of -1. This commonly occurs when the page first loads and an item is not selected by default. Provide code to test this value before referencing the item in the Items collection. Otherwise, an exception is thrown if the index is out of the range of the collection.

sll
  • 61,540
  • 22
  • 104
  • 156
1

Add a runat attribute to your Selct HTML control so that it can be accessable in the codebehind.

 <select id="test" runat="server">
      <option value="a">aaa</option>
      <option value="b">bbb</option>
        <option value="c">cc</option>
    </select>

CODE BEHIND

string dd = test.SelectedIndex.ToString();

This code is tested. :)

Shyju
  • 214,206
  • 104
  • 411
  • 497