Reputation: 53
I have Dropdownlist that has only one element:
<asp:DropDownList CssClass="select2" ID="ddl" runat="server" />
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ddl.Items.Add(new ListItem("text", "value"));
}
}
Also my ddl
gets data from ajax call.
When I'm trying to get changed value from code behind it still returns value of first element.
string value = ddl.SelectedValue; //I got data from ajax call, changed value but it still returns first "value"
But from javascript I can get changed value, so now on every change in my ddl I copy value to hidden field so I can get value from codebehind
$("#ddl").change(function () {
$('#hidden_for_ddl').val($("#ddl").val());
});
Finally I can get selected value from code, is it easier way to solve my problem?
string value = hidden_for_ddl.Value; //returns "selected value"
Upvotes: 0
Views: 1574
Reputation: 23
string value = Empty.String;
foreach (ListItem item in ddl) {
if ((item.Selected == true)) {
value = item.Value;
return;
}
}
This will go through each item and set the string value when it finds one that is selected.
Upvotes: 1