如何使用MVC级联下拉列表(how to use cascading dropdownlist in

2019-10-29 20:28发布

我使用asp.net MVC3,我有在2代表我想基于这个下拉数据的另一个下拉菜单有perform.for例如,如果我选择的国家有显示状态属于这个国家,现在用的是下面的代码在控制器中。

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-")

但通过使用这个我只能够得到国家。

Answer 1:

这是一个很好的jQuery插件 ,可以帮助这...

你不想刷新整个页面每次有人改变了国家下拉 - 一个AJAX调用简单地更新状态下拉是更为人性化。



Answer 2:

jQuery的Ajax是这些类问题的最佳选择。

脚本代码在下面给出

<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>

控制器:

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);
        }


Answer 3:

尝试这个,

<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>

视图

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

调节器

  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);
        }


文章来源: how to use cascading dropdownlist in mvc