Golda
Golda

Reputation: 3881

Set the value to drop down list using Javascript and get that value in C#

    function SetDropDownValue() {
            var opt = document.createElement("option");
            opt.text = "New Value";
            opt.value = "New Value";
            document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
            document.getElementById('<%=DropDownList.ClientID%>').value = val;
    }

The above coding works good for me, The new value append to the drop down list while clicking the button. Then i want to get the drop down value in my code behind(C#). It not working in C#.

    string res = DropDownList.SelectedValue;

In the C# coding displays only empty string ("").

How can i get the dropdown selected value?

Upvotes: 1

Views: 3213

Answers (1)

Adil
Adil

Reputation: 148120

You are changing the html but not the ViewState of the DropDownList that is why you are not getting in asp.net server side code. You can add the value in some hidden field and use that on server side.

HTML

<input type="hidden" id="hdnDDL" runat="server" />

Javascript

function SetDropDownValue() {
    var opt = document.createElement("option");
    opt.text = "New Value";
    opt.value = "New Value";
    document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
    document.getElementById('<%=DropDownList.ClientID%>').value = val;
    document.getElementById('<%=hdnDDL.ClientID%>').value = val;
}

Code behind

string optionValue = hdnDDL.Value;

Upvotes: 2

Related Questions