ASP.NET MVC - Cascading Drop Down
Asked Answered
E

4

7

I'm currently learning ASP.NET MVC and using Nhibernate.

I would like to use Cascading Drop-Down Boxes. Has anyone managed to get cascading drop-down boxes working in MVC?

Updated: I have looked at the following website: link text and used method 1.

Controller Code

        var makeList = new SelectList(makeRepository.ListMakes (), "Id", "make",1);
        ViewData["Makes"] = makeList;

        //// Create Models view data
        var modelList = new CascadingSelectList(modelRepository.ListModels (Convert.ToInt32(makeList.SelectedValue.ToString())), "ModelID","Id", "Name");
        ViewData["Models"] = modelList;

View Code

<%= Html.DropDownList("--Select Make--","Makes")%>
<label for="Makes">Car Model:</label>    
<%= Html.CascadingDropDownList("Models", "Makes") %> 

The correct list of cars is listed when a Make with id of 1 is selected, but when I select a different make the model list is empty?

Excursive answered 1/4, 2009 at 13:43 Comment(2)
Your modelList should contain all models. Right now you select models for the selected (first) make only.Underpass
see that: #5498024Busby
U
8

You may want to read this TIP.

In this tip, Stephen Walter demonstrates three methods of creating cascading dropdown lists. First, he shows you how to alter the list of options displayed by one dropdown list when an option in another dropdown list changes. Second, he shows you how to expose the data for the dropdown lists through a controller action. Next, he shows you how to grab the data for the dropdown lists from web services.

Underpass answered 1/4, 2009 at 13:44 Comment(6)
Thanks, I have used method 1 but when I select the first drop-down box the second remains blank?Excursive
Did you put CascadingDropDownList.js into Content folder?Underpass
Your modelList should contain all models. Right now you select models for the selected (first) make only.Underpass
Thanks, I removed 1 from var makeList = new SelectList(makeRepository.ListMakes (), "Id", "make"); I get an error with var modelList = new CascadingSelectList(modelRepository.ListModels (Convert.ToInt32(makeList.SelectedValue.ToString())), "ModelID","Id", "Name")); as there is no selected value.Excursive
No, no. 1 was where it should be. The problem is with the modelList. It should equal to new CascadingSelectList(modelRepository.GetAllModels(), "ModelID","Id", "Name")); I don't know if your repository has such method, but this is what required for cascading list to work.Underpass
Seems like Stephen Walter's code files are no longer availableFootball
S
4

You might want to have a look at a post I made a couple of weeks ago on exactly this

First we will need to setup the JsonResult controller action.

/// <summary></summary>  
/// Get Models
/// <param name="makeID" />  
/// <returns></returns>  
public JsonResult GetModels(string id)  
{       
   JsonResult result = new JsonResult();       
   var filteredModels = from model in homeViewModel.Models
                        where model.MakeID.ToString() == id
                        select model;       result.Data = filteredModels.ToList();
   result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;    
   return result;  
} 

This method now gives us the ability to use the nifty $.getJSON jquery call. The signature for the call is as follows

jQuery.getJSON( url, [ data ], [ callback(data, textStatus) ] )

Given that we have setup 2 Drop Down Lists, one for Makes and the other for Models, like so.

   Html.DropDownListFor((model) => model.MakeID, new SelectList(Model.Makes, "ID", "Description"))    
   Html.DropDownListFor((model) => model.ModelID, new SelectList(Model.Models, "ID", "Description"))

we can include the following bit of jquery

//Hook onto the MakeID list's onchange event  
$("#MakeID").change(function() {   
   //build the request url   
   var url = '<!--Url.Content("~/")-->' + 'Home/GetModels';

   //fire off the request, passing it the id which is the MakeID's selected item value   
   $.getJSON(url, { id: $("#MakeID").val() }, function(data) {    
      //Clear the Model list    
      $("#ModelID").empty();    
      //Foreach Model in the list, add a model option from the data returned    
      $.each(data, function(index, optionData) {       
         $("ModelID").append("<option value=" + optionData.ID +">"+ optionData.Description +"</option>"  );    
      });
   });  
}).change();

Sorry for the shameless plug :(

Staccato answered 20/5, 2010 at 19:0 Comment(1)
what do you make of this? Trying to use your example. Exception Details: System.ArgumentNullException: Value cannot be null. Parameter name: items @Html.DropDownListFor(model => model.OrigSampID, new SelectList(Model.OrigSampID,"OrigSampID","SampDate"))Tellez
M
2

I have created a jQuery plugin for this.

http://weblogs.asp.net/rajbk/archive/2010/05/20/cascadingdropdown-jquery-plugin-for-asp-net-mvc.aspx

Moot answered 20/5, 2010 at 18:54 Comment(0)
H
1

The Tip you are using: ASP.NET MVC Tip #41 – Create Cascading Dropdown Lists with Ajax from Stephen Walther was not done with MVC Realease 1.0

As such, it works fine with the downloaded project (after fixing some small issues), but when the you try to incorporate into MVC Release 1.0 things break.

For example: in the downloaded project, the scripts are in the Content Folder, in Release 1.0, the scripts are in the Scripts folder.

Also some (if not all) of the *.js files in the release changed from the bets and CTPs. This may be a problem too.

I downloaded his project (fixed a couple of minor issues), and it worked fine within that project (the *.js files).

For Example,

I Fixed the following as:

CHANGE: \Views\Home\index.aspx

<label for="Makes">Car Make:</label>  
<%= Html.DropDownList("--Select Make--", "Makes") %>

TO:

<label for="Makes">Car Make:</label>
<%= Html.DropDownList("Makes", (SelectList)ViewData["Makes"], "--Select Make--")%>

So as you see, there are some issues.

These type problems with tutorials and blogs are abundant; everyone wants to be considered an "Expert" on new technology being released so they write tutorials on betas and CTPs. The result is that the "Expert" will have stuff that doesn't work with the final release.

What you need to find is a Professional that has posted tutorials. A Professional will ensure that their tutorials work. What I mean by a professional is a professional trainer in that area of technology.

Stephen Walther has one of the better blogs and a lot of good stuff, but remember that he is a Microsoift Evangelist. He authors books on MS technology so he needs to be active in the blog world so he puts some good stuff out on leading edge technology. This keeps him deemed as an expert so his books can sell.

Just remember, regardless of the "Expert", there will be inaccuracies in blogs/writings (based on betas and CTPs) when you try to use the information in a final release.

Hightest answered 1/4, 2009 at 13:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.