how to use cascading dropdownlist in mvc

2019-09-01 08:58发布

问题:

am using asp.net mvc3, i have 2 tables in that i want to get data from dropdown based on this another dropdown has to perform.for example if i select country it has to show states belonging to that country,am using the following code in the controller.

ViewBag.country= new SelectList(db.country, "ID", "Name", "--Select--");
 ViewBag.state= new SelectList("", "stateID", "Name");

   @Html.DropDownListFor(model => model.Country, (IEnumerable<SelectListItem>)ViewBag.country, "-Select-")

   @Html.DropDownListFor(model => model.state, (IEnumerable<SelectListItem>)ViewBag.state, "-Select-")

but by using this am able to get only the countries.

回答1:

There is a good jQuery plugin that can help with this...

You don't want to refresh the whole page everytime someone changes the country drop down - an ajax call to simply update the state drop down is far more user-friendly.



回答2:

Jquery Ajax is the best Option for these kind of questions.

Script Code Is Given below

<script type="text/javascript">
     $(function() {
            $("#@Html.FieldIdFor(model => model.Country)").change(function() {
                var selectedItem = $(this).val();
                var ddlStates = $("#@Html.FieldIdFor(model => model.state)");

                $.ajax({
                    cache:false,
                    type: "GET",
                    url: "@(Url.Action("GetStatesByCountryId", "Country"))",
                    data: "countryId=" ,
                    success: function (data) {
                        ddlStates.html('');
                        $.each(data, function(id, option) {
                            ddlStates.append($('<option></option>').val(option.id).html(option.name));//Append all states to state dropdown through returned result
                        });
                        statesProgress.hide();
                    },
                    error:function (xhr, ajaxOptions, thrownError){
                        alert('Failed to retrieve states.');
                        statesProgress.hide();
                    }  
                });
            });
        });
</script>

Controller:

public ActionResult GetStatesByCountryId(string countryId)
        {
            // This action method gets called via an ajax request
            if (String.IsNullOrEmpty(countryId))
                throw new ArgumentNullException("countryId");

            var country = GetCountryById(Convert.ToInt32(countryId));
            var states = country != null ? GetStatesByConutryId(country.Id).ToList() : new List<StateProvince>();//Get all states by countryid
            var result = (from s in states
                          select new { id = s.Id, name = s.Name }).ToList();

            return Json(result, JsonRequestBehavior.AllowGet);
        }


回答3:

Try this,

<script type="text/javascript">
    $(document).ready(function () {
        $("#Country").change(function () {

            var Id = $("#Country").val();
            $.ajax({
                url: '@Url.Action("GetCustomerNameWithId", "Test")',
                type: "Post",
                data: { Country: Id },
                success: function (listItems) {
                    var STSelectBox = jQuery('#state');
                    STSelectBox.empty();
                    if (listItems.length > 0) {
                        for (var i = 0; i < listItems.length; i++) {
                            if (i == 0) {
                                STSelectBox.append('<option value="' + i + '">--Select--</option>');
                            }
                            STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');

                        }

                    }
                    else {
                        for (var i = 0; i < listItems.length; i++) {
                            STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');

                        }
                    }
                }


            });

        });
});
</script>

View

@Html.DropDownList("Country", (SelectList)ViewBag.country, "--Select--")
    @Html.DropDownList("state", new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "-- Select --")

Controller

  public JsonResult GetCustomerNameWithId(string Country)
        {
            int _Country = 0;
            int.TryParse(Country, out _Country);
            var listItems = GetCustomerNameId(_Country).Select(s => new SelectListItem { Value = s.CountryID.ToString(), Text = s.CountryName }).ToList<SelectListItem>();
            return Json(listItems, JsonRequestBehavior.AllowGet);
        }