Click here to Skip to main content
15,911,030 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I have googled this for many hours but could not find an answer. It should be very easy to accomplice. In webforms this is done in seconds.
How do I load multiple dropdownlists in MVC using Ajax.BeginForm() or any other Ajax approach?
Example:
DropDownList 1 = Artist
DropDownList 2 = Album
DropDownList 3 = Title
When the webpage is loaded the following should happen:
1) DropDownList 1 is populated and the first artist is selected,
2) then DropDownList 2 is populated based on the selected artist,
3) and the first avaliable allbum is selected,
4) Then DropDownList 3 is populated based on selected artist and selected album
5) and then the first avilable title is seleced

All of the steps above is done automatically without user interaction. Then if the user changes album all items should be clared in the title-dropdownlist and then populate it based on the titles corresponding to the selected album.

The point is that no dropdownlist can be pre-populated!

In real world there are 5 dropdownlist but could I solve 3 than I could do any number of DropDownLists.

I have seen tons of example when dropdownlist 1 loads and than the user must select a value from dropdownlist 2 to be able to see all options for dropdownlist 3 or that all dropdownlists are pre-populated etc...

I followed this example and got it working, but not for my needs of several dropdownlists that automatically loads with default values. Simple Implementation of MVC Cascading Ajax Drop Down[^]

Again it should be trivial and I'm surprised I could not find the answer!

Thank you for helping me out! This is drivning me crazy...

Regards,
Lars
Posted
Updated 29-Nov-14 1:24am
v4
Comments
Zoltán Zörgő 28-Nov-14 14:55pm    
It is quite simple. Just take one of those examples and modify the the javascript part. For the start post one of those here.
Zombie_Inc 28-Nov-14 16:33pm    
I just don't know where to start. How should I modify this to be able to load more than one dropdownlist at the same time?

<script type="text/javascript">
$('#SelectedClub').change(function () {
$(this).parents('form').submit();
});
</script>

Regards,
Lars
Zoltán Zörgő 29-Nov-14 2:11am    
Ok. The approach in your comment can be also used, but than you have to change the server side to send not only the albums but the titles too. Still, I would take in my hands all flows, and not rely on Ajax.BeginForm, simply because that one is for a general and simple scenario, and here you will probably need more than that.
Zoltán Zörgő 29-Nov-14 7:33am    
As you can see, there are two forms in that solution. It is not a good practice. Not that therea rea multiple forms, but that this way the two sub-lists are functionally separated. It is hard to link them. You should implement ajax calls for the dropdowns directly, and not for forms - or bind all three dropdowns in a single form and populate on postback as necessary.

Hello Mate,
Here is my suggestion for you, I hope this helps you some way.
I have created a fiddle for this. This fiddle is just an example, please check if this helps.
Fiddle[^]
The logic here is, the dropdown should be populated when the DOM is ready or on page load, then when you select a value from Artist dropdown, take the value and then make an ajax call to set the album dropdown value/index as per the value. You can also use switch case statement in javascript if the values are less.
The events to keepin mind are, onChange() and selectedIndex = ''.
Check the fiddle you will get some idea. For the ajax call, you can put the call inside the onchange event fumction. Then accordingly select and set the other dropdown values.
I hope this helps you anyway.
Post back your queries if any.
Thanks
 
Share this answer
 
Comments
Zombie_Inc 29-Nov-14 7:30am    
Thank you Suraj but I could not use this metod I think. Please see my updated more detailed description of what I try to accomplish.
Regards,
Lars
[no name] 29-Nov-14 10:46am    
Ok you could make ajax call on each change event of the dropdown by sending the value selected in the previous dropdown, to get the values of the next dropdown and set the selected Index.
Hi,
After many hours I finally solved it. I don't know if this is a good solution but I thought I should share it anyway.

In controller:
public ActionResult LoadCourse(SettingsModel model)
{
    ...load album model depending on artist here

    return Json(model.Albums, JsonRequestBehavior.AllowGet);
}

public ActionResult LoadCourse(SettingsModel model)
{
    ...load title model depending on album here

    return Json(model.Title, JsonRequestBehavior.AllowGet);
}

The JavaScript:
<script type="text/javascript">

  var Urls = {
    UrlArtist: '@Url.Action("LoadArtists", "Settings")',
    UrlTitle: '@Url.Action("LoadTitles", "Settings")'
  }

  $(function () {
    $("#artistId").change(function () {
      var selectedItem = $(this).val();
      var statesProgress = $("#ajaxLoader");
      statesProgress.show();
      // First ajax call
      $.ajax({
        cache: false,
        type: "POST",
        url: Urls.UrlArtist,
        data: { "ArtistName": selectedItem },
        success: function (data) {
          $("#albumId").html("");
          var $select = $('#albumId');
          $.each(data, function (i, item) {
            $('<option>', {
              value: item.Value
            }).html(item.Text).appendTo($select);
          });
          // Second ajax call
          $.ajax({
            cache: false,
            type: "POST",
            url: Urls.UrlTitle,
            data: { "AlbumName": selectedItem },
            success: function (data) {
              $("#teelist").html("");
              var $select = $('#teelist');
              $.each(data, function (i, item) {
                $('<option>', {
                  value: item.Value
                }).html(item.Text).appendTo($select);
              });
            },
            error: function (xhr, ajaxOptions, thrownError) {
              alert('Failed to retrieve titles.');
            }
          });
          statesProgress.hide();
        },
        error: function (xhr, ajaxOptions, thrownError) {
          alert('Failed to retrieve albums.');
          statesProgress.hide();
        }
      });
    });
  });

</script>

Regards,
Lars
 
Share this answer
 

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