c# - 从用 jquery 填充的 asp.net 下拉列表中获取文本
问题描述
我用 jquery 填充了 asp.net 下拉列表以显示国家和城市。下拉列表显示正确的值。我需要在 asp.net 的后端获取 ddlState 的文本。但是,我无法从下拉列表中获取选定的文本。它说它是空的。
下面是我的脚本。
<script type="text/javascript">
$(document).ready(function () {
GetCountries();
GetStates();
});
function GetCountries() {
$.ajax({
type: "GET",
url: "http://api.geonames.org/countryInfoJSON?formatted=true&lang=en&style=full&username=xxx",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (data) {
$(".ddlCountry").append($('<option />', { value: -1, text: 'Select Country' }));
$(data.geonames).each(function (index, item) {
$(".ddlCountry").append($('<option />', { value: item.geonameId, text: item.countryName}));
});
},
error: function (data) {
alert("Failed to get countries.");
}
});
}
function GetStates() {
$(".ddlCountry").change(function () {
GetChildren($(this).val(), "States", $(".ddlState"));
});
}
function GetChildren(geoNameId, childType, ddlSelector) {
$.ajax({
type: "GET",
url: "http://api.geonames.org/childrenJSON?geonameId=" + geoNameId + "&username=xxx",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (data) {
$(ddlSelector).empty();
$(ddlSelector).append($('<option />', { value: -1, text: 'Select ' + childType }));
$(data.geonames).each(function (index, item) {
$(ddlSelector).append($('<option />', { value: item.geonameId, text: item.name + "," + item.countryCode }));
});
},
error: function (data) {
alert("failed to get data");
}
});
}
</script>
以下是我拥有的两个下拉列表。
<asp:DropDownList
runat="server"
ID="ddlCountry"
CssClass="ddlCountry">
</asp:DropDownList>
<br />
<asp:DropDownList
runat="server"
ID="ddlState"
onChange="ddlState_OnChange"
CssClass="ddlState">
</asp:DropDownList>
有人可以帮忙吗?谢谢你。
解决方案
您的“更改”函数不应位于 GetStates() 函数中。每次用户更改选择时,您都应该收集该值。然后用实际值触发 GetStates。
$(".ddlCountry").change(function () {
valueOfddlCountry = $(this).val();
});
推荐阅读
- javascript - ngForm 变量在组件中未定义
- python - 如何使用 python 编辑保存在 Elasticsearch 中的文档
- scala - 组合 2 KeyValueGroupedDatasets
- cypress - 使用测试运行程序在本地运行时在仪表板中记录测试结果
- python - 解开一个 numpy mgrid
- python - 无法在树莓派 yocto 构建中导入 python tty 模块
- jquery - 如何在这里修复画廊?
- flutter - 覆盖页面浏览控制器的 CustomPainter 画布
- operating-system - printf, scnaf,,(stdio.h中的I/O函数)可以调用API吗?
- javascript - 将动态加载的模型移动到查看器中