MVC4 Ajax DropDownList

The MVC Ajax DropDownList populates a second DropDownList (onchange) by calling a predifined url in the background. It requires minimal configuration and is easy to use.

The parent DropDownList receives an AjaxUpdateOptions object. The AjaxUpdateOptions object contains the name of the child DropDownList (the list that will be populated when the value of the parent changes). It also contains the url to call when the value of the parent DropDownList changes.

 

Parent DropDownList:

@using Share.Bonnet.AjaxDropDownList;

@Html.DropDownListFor(
            model => model.Country,
            Model.CountryList,
            new {
                @class = "form-control"
            },
            Ajax.UpdateActionFor(
                model => model.City,
                new AjaxUpdateOptions {
                    DisableTargetWhenEmpty = true,
                    Url = Url.Action("CitySelectListJson")
                }
            )
)

Note! The Ajax.UpdateActionFor(model => model.Property) is a conviniance method. We could just as well create an AjaxUpdateOptions object and set the Target property to "City"

 

Child DropDownList:

@Html.DropDownListFor(
            model => model.City,
            Model.CityList,
            new {
                @class = "form-control",
                disabled = "disabled"
            }
)

 

To get things working we need to reference the Javascript file jquery.bonnet.ajax-dropdownlist.js that is shipped with this package. The easiest way to do so is to add a bundle in the App_Start/BundleConfig.cs file.

 

In App_Start/BundleConfig.cs add:

bundles.Add(new ScriptBundle("~/bundles/bonnet").Include(
                      "~/Scripts/jquery.bonnet*"));

 

In the View or Layout file add:

@Scripts.Render("~/bundles/bonnet")

 

Note! The @Scripts.Render("~/bundles/bonnet") must appear after @Scripts.Render("~/bundles/jquery")


Tip!
Download the Source for a working example

That's all there is too it!

Last edited Aug 29, 2014 at 8:04 AM by FrankBonnet, version 6