2

I'm trying to populate on dropdown(i.e dropdown2) on the value basis of other dropdown(i.e dropdown1), It's populate fine,now my problem is when i'm click on asp button to get the selected value of dropdown 2 it will be return blank value, I'm not not understand what is going wrong?

HTML

<select runat="server" id="ddlFilter" ClientIDMode="Static">
    <option value="0">Both</option>
    <option value="1">Add new</option>
    <select runat="server" id="ddlDepartment" ClientIDMode="Static"></select>
    <asp:Button ID="btnSearch" runat="server" Text="Show Report" CssClass="search_btn" onclick="btnSearch_Click" />

JS

<script>
$(document).ready(function () {
    $("#ddlFilter").change(function () {
        if ($("#ddlFilter").val() > 0) {
            $("#ddlDepartment").append( < option > New < option > );
        }
    });
});
</script>

C#

protected void btnSearch_Click(object sender, EventArgs e) {
    string val= ddlDepartment.Value;
}
putvande
  • 15,068
  • 3
  • 34
  • 50
Ajay Rawat
  • 59
  • 2
  • 14

5 Answers5

6

You can't get selected value from dropdown if you adding options in javascript. you can use:

string selectedValue = Request.Form[ddlDepartment.UniqueID];

See Question

Community
  • 1
  • 1
Deepak
  • 186
  • 3
1

change this

if ($("#ddlFilter").val() > 0) 

to

if ($(this).val() > 0) 

change this

 $("#ddlDepartment").append( < option > New < option > );

to

$("#ddlDepartment").append( '<option>New</option>');
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
  • You not read my question clearly i say my drop down work properly but d'nt get value properly on button click – Ajay Rawat Aug 16 '13 at 08:57
  • It's a viewstate issue. Actually, if you do a `ddlDepartment.Items.Count` you will always get 0 in code behind, since in the viewstate there's no option added to the dropdown on initial page load. – palaѕн Aug 16 '13 at 09:02
1

If you want to get the value from the drop down list in the C# code behind you need to add the new item on the first drop down lists SelectedIndexChanged event and add the "New Option" to the dropdowns item collection.

The steps would be:

1) add SelectedIndexChanged for ddlFilter
2) Check if the value for ddlFilter is "1"
3) If the value is "1" add "New Option" ListItem to the dropdownlist name ddlDepartment.

Then when the button is pressed you should get the selected value as item is now in the dropdown's list collection.

dotnethaggis
  • 1,000
  • 12
  • 26
1

Try likes this ,

ddlFilter.Items[ddlFilter.SelectedIndex].Text;

will return your string text Both,Add new

ddlFilter.Items[ddlFilter.SelectedIndex].value;

will return your value 0,1

zey
  • 5,939
  • 14
  • 56
  • 110
0

You will find 100's of solutions for dropdown,

In c# : String Val=ddlDepartment.SelectedItem.Value;

Sabyasachi Mishra
  • 1,677
  • 2
  • 31
  • 49
shiva kumar
  • 74
  • 1
  • 5