Dynamic Drop Down List Boxes in MVC

I needed two drop down lists on my page, so my view has these two drop-down lists:

In the database Media Type is parent of/to Media Format i.e. each type has it's format list

Requirement - when the user changes type, limit format list to child items only.

In the view I have the 2 drop-down lists (DDLs):

Each DDL has an id.

To intercept the drop-down change event of the first (id = "MediaTypeDDLDiv") we need some java script at the end of the file:

Not easy to read, but the flow goes like this:

IF MediaFormatDDLDiv changed then // using #MediaFormatDDLDiv
   send a post to the server to request the required data to populate the other DDL
   IF success then
     add the null item (not selected)
     add each item returned
   else error

Looking at the actual script code:

var url = '@Url.Action("PopulateFormatDDL", "Media")'; // use the helper (dont hard code)

The function being called is PopulateFormatDDL in my MediaController (NB referenced as Media only i.e. don't use MediaController)

var formats = $('#MediaFormatDDLDiv');

A pointer to my second list DDL

var selectedMediaTypeID = this.value;

The currently selected value of the first DDL

$.getJSON(url, { id: selectedMediaTypeID }, function (data)

So magic function here to processes the url action and passes the selected item on the first list.

The getJSON() method is used to get JSON data using an AJAX HTTP GET request.

In the Controller I have

        public ActionResult PopulateFormatDDL(int? id)
            if (id == null) id = 0;

            var mediaFormats = GetMediaFormats(id);

            var retSelectList = new SelectList(mediaFormats, "FormatID", "FormatName");

            return Json(retSelectList, JsonRequestBehavior.AllowGet);

JSON (JavaScript Object Notation) is an efficient data encoding format that enables fast exchanges of small amounts of data between client browsers and AJAX-enabled Web services.

I did have some trouble getting this working, mainly due to the use of var - my mistake was in returning a list of the actual records from GetMediaFormats(id) - oo-overload!!!

© 2018 - StartledCat