ASP.NET MVC Cascading drop down lists

Found this great post on how to create cascading drop downs in ASP.NET MVC.

I created a page for looking up shipping rates by carrier, weight and zip code. For my particular usage, I had 2 lists: Carrier and ShipMethod. I wanted the cascading list to be disabled when the initial list selection had yet to be made. I created functions to populate the target list as well as enable/disable the target list. I made the js into a reusable Razor helper which should allow me to use it anywhere I need this functionality.

Here is the helper code:

@helper DynamicDropDowns() {
<script type="text/javascript">
    function listChanged($list, $target, url) {
        var listId = $list.val();
        if (listId == "") { // User selected first option, 
                            // so clear and disable the list
            $target.empty();
            enableList($target, false);
            return;
        }
        $.getJSON(url, { id: listId }, function (data) {
            $target.empty(); // Clear the list
            $.each(data, function (idx, item) { // Add the data
                $target.append($("<option/>",
                {
                    value: item.Value,
                    text: item.Text
                }));
            });
            enableList($target, true); // Enable the list
        });
    }

    function enableList($list, enabled) {
        $list.attr("disabled", enabled ? null : "disabled");
    }
</script>
}

Gist

And here it is in action:

<script type="text/javascript">
    $(function () {
        var $carrier = $("#Carrier");
        var $ship = $("#ShipMethod");
        enableList($ship, false);
        $carrier.change(function () {
            listChanged($(this), $ship, "/Tools/GetShipMethodsByCarrier");
        });
    });
</script>