我的客户端有一个文本框和一个下拉列表。我需要使用 javascript 将这些控件的值传递给 web 方法(在后面的代码中)。 我可以传递文本框值,但不能传递下拉列表。
<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>
这是我的 WebMethod 中的代码
[WebMethod]
public static IEnumerable<string> callJS(string search)
{
IEnumerable<string> results = itemList.Where(item => item.Contains(search.ToLower()));
return (results);
}
最佳答案
您可以像这样获取 DDL 的值:
var liste = document.getElementById('#ddlList');
var ddl = liste.options[liste.selectedIndex].value;
编辑:
为了从 DDL 中检索所有值,我们必须遍历选项值:
var ddl = [];
for(var i = 0; i<3; i++) {
ddl.push(document.getElementById("<%=ddlList.ClientID %>").options[i].value);
}
这个数组可以在服务器端作为 List<string>
获取:
[WebMethod()]
public static IEnumerable<string> callJS(List<string> ddl) { ... }
关于javascript - 如何通过javascript将客户端的dropDownList的值传递给webmethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13686426/