Filter DDL items using javascript and a Dictionary<string, string> object in the ViewBag

I had a need to modify the options on a DDL based on different selections the user had made on the page.  I did this at runtime by passing in a list of menu items in the ViewBag and using javascript to add and remove items based on the users selections.

Step 1: Create a ViewBag Dictionary <string, string> object that contains the full list of possible menu items.

ViewBag.MenuItems = new Dictionary<string, string> {
     {"option1", "Option One"},
     {"option2", "Option Two"}, 
     {"option3", "Option Three"}, 
     {"optionShowMe", "Option Show Only Me"}, 
};

Step 2: Create a javascript function that will insert an item into the DDL

function AddItem(Text,Value)
{
    // Create an Option object
    var opt = document.createElement("option");
    
    // Add an Option object to Drop Down/List Box
    document.getElementById("DropDownList").options.add(opt);

    // Assign text and value to Option object
    opt.text = Text;
    opt.value = Value;
}

Step 3: Create a method that will filter the options based on the users selection

function FilterDropDownListItems() {
    var array = @(Html.Raw(Json.Encode(ViewBag.MenuItems)));
    var userSelectedOption = $('#UserDDL').val();
    $("#DropDownList").empty();

    if (userSelectedOption === '140') {
        for (var val in array) {
            if(val === 'optionShowMe')
                AddRequestTypeItem(array[val], val);
        }
        $('#DropDownList').val('optionShowMe');
    } else {
        AddRequestTypeItem('Please Select', '');
        for (var val in array) {
            if(val != 'optionShowMe')
                AddRequestTypeItem(array[val], val);
        }
        $('#DropDownList').val('');
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s