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.

gusadolfo
  • 65
  • 1
  • 4
  • 11

2 Answers2

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

Community
  • 1
  • 1
Adam Tal
  • 5,911
  • 4
  • 29
  • 49
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.

Dmitry Efimenko
  • 10,973
  • 7
  • 62
  • 79
  • "Go google it" isn't an answer. – asawyer May 23 '13 at 22:06
  • 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. – Adam Tal May 23 '13 at 22:16
  • @AdamFridental http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers – asawyer May 23 '13 at 22:18
  • 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 =\ – Adam Tal May 23 '13 at 22:20
  • @AdamFridental Looks much better now, +1 for effort. The question does look to be a duplicate so go ahead and vote. – asawyer May 23 '13 at 22:28
  • Hi @AdamFridental thanks a lot for the reply and all the other replies!! I didn't vote down the answer I'm just checking it out right now. I will try this later because there have been some changes on the project and I need to change a few things before I dive into this issue. I will let you know if this helped me. I didn't find the other answers because I was looking for chained dropdowns instead of cascade dropdowns, I will also take a look at the other posts. Thanks a lot for taking time and answering this post I really appreciate it. – gusadolfo May 24 '13 at 21:45