Click here to Skip to main content
14,696,792 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I need to use dropdown with OptionGroup in asp.net MVC4.
i have Googled this and i got that there is no support in dropdownlist for this functionality.

I will be thankful if anyone can help me that how can i achieve this in MVC4.

Thanks in Advance.
Posted
Updated 3-Sep-14 4:02am
v3

1 solution

I am Adding And Accepting this as Solution to help others who are seeking for the same...


While Searching on this i have founded few ways..

1.
By Creating your own HTML Helper you can achieve the functionality.
And After Searching for i have founded one HTML Helper developed by another developer from this link...https://github.com/bhaumikpatel/DDL.optgroup.MVC.Demo[^]

2.
The Second way was to get data from Ajax request and binding it by JQTemplate.
I have found useful link to do this...
http://stackoverflow.com/questions/7634137/two-dimensional-list-inside-jquery-template[^]

3.
I have done this by Creating dynamic HTML after getting data by $.POST...

Controller Method code...
// I have taken Tuple that will construct data for me...
// List<Tuple<OptionGroupName, OptionValueArray, OptionTextArray>>
List<Tuple<string, int[], string[]>> datalist = new List<Tuple<string, int[], string[]>>();


//Then Added Data To This Tuple like...
datalist.Add(new Tuple<string,>("Job1", new int[] {1,2,3}, new string[] {"Batch1","Batch2","Batch3"}));

return Json(datalist);


And My Ajax call is like...
$.ajax({
        type: 'POST',
        url: "/" + controller + "/" + action + "/" + id,
        success: function (data) {

            // <OptionGroup Label:JobName></OptionGroup> 
            // <Option Value:BatchID>Content:BatchName></Option>


            var _Content = '<select name="BatchID" id="BatchDropDown" ><option value="">Select Batch</option>';

            $(data).each(function (x) {
                var tupple = data[x];
                _Content = _Content + '<optgroup label="' + tupple.Item1.toString() + '">';

                var columns = tupple.Item3;
                $(columns).each(function (y) {
                    _Content = _Content + '<option value="' + tupple.Item2[y] + '">' + columns[y] + '</option>';
                });
                _Content = _Content + '</optgroup>';

            });

            _Content = _Content + '</select>';
            $('#divBatch').append(_Content);

            //Binding Event to Newly Created Batch DropDown
            $("#BatchDropDown").bind("change", function () { ChangeBatch($(this).val()); });

        },
        
    });
   
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900