Populating Dropdownlist Using MVC2 Based On Another Dropdownlist (Cascading DropDownList)

后端 未结 3 1350
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 08:46

I am making an application that deals with vehicles. I need two DropDownLists:

  • Makes: All Vehicle Makes
  • Models: Models that belong to the selected
3条回答
  •  余生分开走
    2020-12-08 09:15

    This is what I ended up doing... Didn't need additional plugins / 1000 Lines of code...

    The Html

    //The first DDL is being fed from a List in my ViewModel, You can change this...
    <%: Html.DropDownList("MakeList", new SelectList(Model.Makes, "ID", "Name")) %>
    
    

    The JQuery

        $(document).ready(function () {
            $('#MakeList').change(function () {
                $.ajaxSetup({ cache: false });
                var selectedItem = $(this).val();
                if (selectedItem == "" || selectedItem == 0) {
                    //Do nothing or hide...?
                } else {
                    $.post('<%: ResolveUrl("~/Sell/GetModelsByMake/")%>' + $("#MakeList > option:selected").attr("value"), function (data) {
                        var items = "";
                        $.each(data, function (i, data) {
                            items += "";
                        });
                        $("#ModelID").html(items);
                        $("#ModelID").removeAttr('disabled');
                    });
                }
            });
        });
    

    The Action

        [HttpPost]
        public ActionResult GetModelsByMake(int id)
        {
            Models.TheDataContext db = new Models.TheDataContext();
            List models = db.Models.Where(p=>p.MakeID == id).ToList();
    
            return Json(models);
        }
    

提交回复
热议问题