对MVC级联下拉列表进行疑难解答不会填充

时间:2017-05-29 04:58:11

标签: javascript json asp.net-mvc asp.net-mvc-5 cascadingdropdown

我的MVC局部视图中有两个下拉列表,它包含在我的MVC项目的Area文件夹下。第一个下拉列表是DB填充的,第二个下拉列表应该从Json控制器函数中包含的静态列表中填充。但是,我似乎无法填充它。任何建议,将不胜感激。

Screenshot

部分视图下拉列表

    <div class="form-group">
    @Html.DropDownList("CommonHerps", new SelectList(Model.CommonHerpNames, 
   "CommonHerpId", "HerpName"), "Select Animal", new {@class = "form-control"})
    </div>

应根据上面的选择

填充此内容
 <div class="form-group">
   @Html.DropDownList("ReptileSpeciesList", new SelectList(string.Empty, 
   "Value", "Text"), "Select Animal", new {@class = "form-control"})
   </div>

控制器Json

 public JsonResult GetGenericSpecies(int cAnimalID)
    {

        List<SelectListItem> genericSpecies = new List<SelectListItem>();
        switch (cAnimalID) 
        {
            case 4:
                    genericSpecies.Add(new SelectListItem { Text= "Burmese Python", Value = "1"});
                    genericSpecies.Add(new SelectListItem { Text= "Reticulated Python", Value = "2"});
                break;
            case 3:
                    genericSpecies.Add(new SelectListItem { Text= "Panther Chameleon", Value = "3"});
                    genericSpecies.Add(new SelectListItem { Text= "Panther Chameleon", Value = "4"});
                break;
        }
        return Json(new SelectList(genericSpecies, "Value", "Text"));

    }//End GetGenericSpecies

JS Script Block

@section Script{

    <script src="~/Scripts/jquery-1.10.2.js" type="text/javascript"></script>
    <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#CommonHerps").change(function () {
                $("#ReptileSpeciesList").empty();
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("/GetGenericSpecies")',
                    datatype: 'json',
                    data: { cAnimalId: $("#CommonHerpId").val() },
                    //Get the value of the common species list and pass it to JSON method as expected property. 

                    success: function (species) {
                        //species contains the list of common species names and the scientific order.

                        $.each(species, function (i, species) {
                            $("#species").append('<option value="' + species.Value + '">' + species.Text + '</option>');
                            //Add option for species. 
                        });
                    },
                    error: function (ex) {
                        alert('Failed to retrieve species.' + ex);
                    }
                });
                return false;
            })

        });
    </script>
}

0 个答案:

没有答案
相关问题