1

DropDownList with some Categories loaded and i need to populate another @Html.DropDownList depending on the option selected on the 1st dropdown.

This is the code I use to populate the 1st dropdown:

On the Controller:

        TecnicService ListCategory = new TecnicService();
        IList<Category> resultCat = ListCategory.GetCategory();

        List<SelectListItem> CatDropDown = new List<SelectListItem>();

        foreach (Category in resultadoCat)
        {
            CatDropDown.Add(new SelectListItem
            {
                Value = a.Id.ToString(),
                Text = a.Name.ToString()
            });
        }

On the View:

  @model APP.Models.DataViewModel  
    @using (Html.BeginForm("NewPol", "Tecnic", null, FormMethod.Post, new { id = "pol-data-form", @class = "form-horizontal" }))
    {
    <div class="control-group">
             <label for="category" class="control-label">Category</label>              
             <div class="controls">
                  @Html.DropDownList("BasicData", Model.Category, new { @class= "required", name="category"})
             </div>               
        </div>    
        <div class="control-group">
             <label for="ram" class="control-label">Ram</label>
              <div class="controls">
                  @Html.DropDownList() WHAT DO I DO HERE???????
              </div>
        </div>
.
.}

I get the data through a service which returns a List, now I need to populate the 2nd dropdown depending on the selection of the 1st dropdown.

0

2 Answers 2

4

What you're looking for is called Cascading Drop Down List.

You can create a jQuery plugin that will track the changes and send the server an ajax request to get the values for the other drop down:

(function ($) {
    $.fn.cascade = function (options) {
        var defaults = { };
        var opts = $.extend(defaults, options);

        return this.each(function () {
            $(this).change(function () {
                var selectedValue = $(this).val();
                var params = { };
                params[opts.paramName] = selectedValue;
                $.getJSON(opts.url, params, function (items) {
                    opts.childSelect.empty();
                    $.each(items, function (index, item) {
                        opts.childSelect.append(
                            $('<option/>')
                                .attr('value', item.Id)
                                .text(item.Name)
                        );
                    });
                });
            });
        });
    };
})(jQuery);

And then simply wire it up:

$(function () {
    $('#SelectedProvinceId').cascade({
        url: '@Url.Action("Cities")',
        paramName: 'provinceId',
        childSelect: $('#SelectedCityId')
    });

    $('#SelectedCityId').cascade({
        url: '@Url.Action("Suburbs")',
        paramName: 'cityId',
        childSelect: $('#SelectedSuburbId')
    });
});

Source: Cascading drop-downs in MVC 3 Razor view

Some more sources from a simple google search:

AJAX Cascading with MVC4

http://www.sidecreative.com/Blog/Entry/Cascading-dropdown-lists-with-MVC4-and-jQuery

http://www.codeproject.com/Articles/258172/Simple-Implementation-of-MVC-Cascading-Ajax-Drop-D

Sign up to request clarification or add additional context in comments.

Comments

0

It is usually done with ajax. You can do it either your self by writing some JQuery code or using one of the many plugins that you can do on the web to do that.

As a side note, I notice that you use TwitterBootstrap. Check out TwitterBootstrapMvc. You might find it useful.

Wonder why Adam's answer got downvoted. He actually gave a good answer. Wonder if gusadolfo downvoted it because no code was provided. If that was the case, gusadolfo, do not count on code. We can guide you, fix a mistake that you made somewhere, but don't expect us to do your job completely.

6 Comments

"Go google it" isn't an answer.
Thanks for your support :) @asawyer - As a programmer I think that "Go google it" is always the answer, but as SO is a place others arrive to from googling, I belive the answer should have as much information as possible - you can see I gave him 4 links (2 of them to 2 other question in SO) to provide him with different choices.
Ok @asawyer I accept your argument, I will provide some more information next to the links. Though now I belive I should just state it is a duplicate question =\
@AdamFridental Looks much better now, +1 for effort. The question does look to be a duplicate so go ahead and vote.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.