首页 > 解决方案 > 从用 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>

有人可以帮忙吗?谢谢你。

标签: c#jqueryasp.net

解决方案


您的“更改”函数不应位于 GetStates() 函数中。每次用户更改选择时,您都应该收集该值。然后用实际值触发 GetStates。

$(".ddlCountry").change(function () {
         valueOfddlCountry = $(this).val();

});

推荐阅读