I have a textbox and a dropdownlist on my client side. I need to pass the values of these controls to a webmethod (in the code behind) using javascript.
I can pass the textbox value but not the dropdownlist.
<p><asp:DropDownList id="ddlList" runat="server"></asp:DropDownList></p>
<p><asp:TextBox ID="txtSearch" runat="server" OnTextChanged="txtSearch_TextChanged" OnKeyPress="onKeyFunction();" AutoPostBack="True"></asp:TextBox>
<asp:GridView ID="grdLista" runat="server"></asp:GridView>
<script type="text/javascript">
function onKeyFunction() {
var search = document.getElementById('<%=txtSearch.ClientID %>').value;
//var ddl = i need to pass the dropdownlist values here..
PageMethods.callJS(search, /*ddl */, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something wrong.');
}
}
</script>
And this is the code in my WebMethod
[WebMethod]
public static IEnumerable<string> callJS(string search)
{
IEnumerable<string> results = itemList.Where(item => item.Contains(search.ToLower()));
return (results);
}
You can get the value of your DDL like this :
EDIT :
In order to retrieve all the values from a DDL, we have to loop over the options values:
This array can be get at server side as a
List<string>: