Sunday, 29 May 2016

Cascading Dropdown

<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>

@Html.DropDownList("Country", (IEnumerable<SelectListItem>)ViewBag.dropdownbind, "--Choose Your Country--")
@Html.DropDownList("State", (IEnumerable<SelectListItem>)ViewBag.DropdowndataState, "--Choose Your State--")


<script type="text/javascript">

    $(document).ready(function () {
        $('#State').css('display', 'none');
        //Dropdownlist Selectedchange event
        $("#Country").change(function () {
            $("#State").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetStates")', // we are calling json method
                dataType: 'json',
                data: { id: $("#Country").val() },
                // here we are get value of selected country and passing same value as inputto json method GetStates.
                success: function (states) {
                    if (states.length == 0) {
                        $('#State').css('display', 'none');
                        alert("Country doesnt have any state");
                    }
                    else {
                        $('#State').css('display', 'block');
                        // states contains the JSON formatted list
                        // of states passed from the controller
                        $.each(states, function (i, state) {

                            $("#State").append('<option value="' + state.Value + '">' +
                                 state.Text + '</option>');
                            // here we are adding option for States
                        });
                    }
                },
                error: function (ex) {
                    alert('Failed to retrieve states.' + ex);
                }
            });
            return false;
        })
    });

</script>

No comments:

Post a Comment