Cascading DropDown List的初始值

时间:2015-07-26 18:08:53

标签: asp.net-mvc

我的代码工作正常,但在我选择任何国家/地区并选择默认值为选择国家/地区后,状态下拉列表不会被清除,它仍会显示旧值。

控制器:

 public ActionResult Countries()
    {
        List<Countries> objCountries = new List<Countries>();
        objCountries.Add(new Countries { CountryId = 1, CountryName = "India" });
        objCountries.Add(new Countries { CountryId = 2, CountryName = "Japan" });
        objCountries.Add(new Countries { CountryId = 3, CountryName = "France" });
        ViewBag.counties = new SelectList(objCountries, "CountryId", "CountryName");
        return View();

    }

    public JsonResult States(int id)
    {
        List<States> objstates = new List<Models.States>();
        objstates.Add(new States { CountryId = 1, StateName = "Hyderabad" });
        objstates.Add(new States { CountryId = 1, StateName = "Chennai" });
        objstates.Add(new States { CountryId = 2, StateName = "JapanState1" });
        objstates.Add(new States { CountryId = 2, StateName = "JapanState2" });
        objstates.Add(new States { CountryId = 3, StateName = "FranceState1" });
        objstates.Add(new States { CountryId = 3, StateName = "FranceState2" });
        var state = from s in objstates where s.CountryId == id select s;
        return Json(new SelectList(state.ToArray(), "CountryId", "StateName"),
            JsonRequestBehavior.AllowGet);
    }

查看:

<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
 <script>
$(document).ready(function () {
    $("#counties").change(function () {
        $.getJSON('/Cascading/States/' + $("#counties").val(), function (data) {
            var items = '<option>Select a State</option>';
            $.each(data, function (i, state) {
                items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
            });
            $("#States").html(items);
        });

    });
});

<h2>Countries</h2>

 @Html.DropDownList("counties", "select Country")

<select id="States"></select>

1 个答案:

答案 0 :(得分:0)

此代码应该有效:

$('#countries').change(function () {
                jQuery.getJSON('/Cascading/States/', { id: $(this).val() }, function (data) {
                    $('#States').empty();
                    jQuery.each(data, function (i) {
                        var option = $('<option></option>').attr("value", data[i].data[i].Value).text(data[i].Text);
                        $("#States").append(option);
                    });
                });
});