Mvc 4.0中的级联下拉列表

时间:2014-06-20 11:48:22

标签: javascript jquery asp.net-mvc-3 asp.net-mvc-4

我一直在尝试级联下拉列表。为此我在.cshtml页面中使用javascript。不知道是什么原因,我甚至无法调用Js方法,单独留下后来需要在Js方法中调用的控制器方法。下拉列表正在获取州和城市数据,但我没有按照选定的状态获得城市。

<div class="editor-label">
    @Html.LabelFor(model => model.State_Id)
</div>
<div class="editor-field">
    @Html.DropDownList("State",null,"Select State", new {@class="span4", id="State"})
    @Html.ValidationMessageFor(model => model.State_Id)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.CityId)
</div>
<div class="editor-field">
    @Html.DropDownList("City",null,"Select City", new {@class="span4", id="City"})
    @Html.ValidationMessageFor(model => model.CityId)
</div>

<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript" >
    $(document).ready(function(e) {
        $("#State").change(function (e) {
            var selectedValue = $(this).val();
            if(selectedValue != "Select") {
                $.ajax({
                    url: '@Url.Action("GetCities","Employer")',
                    type: 'Post',
                    //data:  { "selectedValue": selectedValue},
                    data: {id: $("#State").val()},
                    dataType: 'json',
                    success: function(response) {
                        var items = "";
                        $.each(response, function(i, city) {
                            $("#City").append('<option value="' + city.Value + '">' + city.Text + '</option>');
                        });
                    },
                    error: function (ex) {
                        alert("Failed To Receive States" + ex);
                    }
                });  
            }
        });
    });
</script>

2 个答案:

答案 0 :(得分:1)

下拉列表是他们自己的野兽。您可能需要使用循环内部的标准DOM方法而不是jQuery的追加方法来创建新的OPTION:

                success: function(response) {
                    var items = "", option, $city = $("#City");
                    $.each(response, function(i, city) {
                        option = document.createElement("option");
                        option.value = city.Value;
                        option.innerHTML = city.Text;
                        $city.append(option);
                    });
                },

答案 1 :(得分:1)

@Html.DropDownListFor(x => x.LeagueId, Model.LeagueSL, "--Select League--", new { id = "ddlLeague"})

@Html.DropDownListFor(x => x.LeagueId, Model.DivisionSL, "--Select Division--", new { id = "ddlDivision"})

第二个DropDownList为空,它只有选项Label --Select Division -

在第一个下拉列表的更改事件中,创建一个填充第二个下拉列表的AjaxRequest。

        var value = $("#DropDown1").val();
        var ddlDivision = $("#DropDownDivision");
            ddlDivision.html('');//clear current contents; 
 $.ajax({
            url: "/Home/GetDivisions",
            type: "GET",
            data: { leagueId: value },
            success: function (data) {

                $.each(data, function (index, item) {
                    //item = this        
                    //populate ddl                                          
                    ddlDivision.append($('<option></option>')
                   .val(item.PropTwo)
                   .html(item.PropOne));
                });
        });

        public JsonResult GetDivisions(int leagueId)
        {    
            using (BaseballEntities context = new BaseballEntities())
            {

                var divisions = (from x in context.Table
                                 where x.LeagueID == leagueId
                                 select new 
                                 {  
                                   PropOne = x.DivisionName,
                                   PropTwo = x.DivisionId
                                 }).ToList();


                return Json(divisions, JsonRequestBehavior.AllowGet);
            }            
        }

编辑:作为旁注,最好使用模型来填充dropdownList。 为您的模型提供SelectList属性

 public List<SelectListItem> LeagueSL { get; set; }//you will need to initialize in constructor

 public ActionResult Index()
 {
             MyViewModel model = new MyViewModel();

              using (MyEntities context = new MyEntities())
             {
                var leagueList = context.League.ToList();

                foreach (var item in leagueList)
                {
                   model.LeagueSL.Add(new SelectListItem() { Text = item.LeagueName, Value = item.LeagueId.ToString() });
                }

             }
        return View(model);
    }