Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

MVC 3 is becoming hugely popular thanks to Razor and the Helpers that make building web applications much easier. One of the common requirements in web development, both with web forms as well as MVC based development, is the cascading dropdownlist. Now, for Web Forms, we can use a variety of options viz. server side programming, jQuery or using the AJAX Control Toolkit’s cascading dropdownlist control for accomplishing this.

I saw a few samples on the internet that used the erstwhile Microsoft AJAX Library along with MVC and also few more samples which used hard coded values for wiring up the cascading dropdown. I have built this sample using Database with 3 tables i.e. Cars, Makes & Colours. The colours table is actually redundant but for the sake of showing a 3 dropdown hierarchy I have made it a relational table – just for the purpose of the sample. Also, all the cars mentioned are the brands that I could recollect and driven around in India Smile

To begin with, lets examine the Database – CascadeSample. It has 3 tables

i. Cars

ii. Models

iii. Colours

I filled in some sample data. At the end of this post, I would provide link for downloading the database scripts as well as the solution.

First, lets create our MVC 3 Application using “File – New Project – ASP.NET MVC 3 Web Application” give it a name “CascadingDropdownSample” and select the “Internet Application” and click ok. This would create the basic scaffolding structure with Membership API. We won’t need it though.

As always with MVC, lets build the Model by right click Models Folder – Add – New Item and search for ADO.NET Entity in the search box of the Dialog.

Chose the ADO.NET Entity Data Model Template and give it a name CarModel.edmx and click Add.

Choose the “Generate from Database” option and in the Next steps, connect to the CascadeSample database and select all the 3 tables and then finish the steps to generate the Entity Model. Our Entity Model is now ready.

Next step is to start wiring up the Controller Actions. For the purpose of this simple demo, lets just use the default HomeController.

Lets add using CascadingDropdownSample.Models; to the namespaces in the HomeController.

Lets add CascadeSampleEntities cse = new CascadeSampleEntities(); within the class

Lets add the following within the Index Action.

public ActionResult Index()
{

ViewBag.Cars = cse.Cars.ToList();
ViewBag.Models = cse.Models.ToList();
ViewBag.Colours = cse.Colours.ToList();
return View();
}

 

Lets switch to the View (ROOT – Views – Home – Index.cshtml) and edit it to look as follows:-

@model CascadingDropdownSample.Models.CascadeSampleEntities
@{
ViewBag.Title = "Home Page";
}

<h2>Cars</h2>
<p>
@Html.DropDownListFor(Model => Model.CarId, new SelectList(ViewBag.Cars as System.Collections.IEnumerable, "CarId", "CarName"),
"Select a Car", new { id = "ddlCars" })
</p>

When we run the page, we will get to see the List of cars in the dropdown.

For the next set of actions i.e. populating the Model and Colour, we need the following Methods.

private IList<Model> GetModels(int id)
{
return cse.Models.Where(m => m.CarId == id).ToList();
}

private IList<Colour> GetColours(int id)
{
return cse.Colours.Where(c => c.ColourId == id).ToList();
}

The next main thing we need is Action methods which can send a JSon Result for both Models and Colours.

To first get the Models by car, we add the following to the HomeController

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadModelsByCar(string id)
{
var modelList = this.GetModels(Convert.ToInt32(id));

var modelData = modelList.Select(m => new SelectListItem()
{
Text = m.ModelName,
Value = m.ModelId.ToString(),

});

return Json(modelData, JsonRequestBehavior.AllowGet);
}

 

and to get the Colours for the various Models, we add


[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadColoursByModel(string id)
{
var colourList = this.GetColours(Convert.ToInt32(id));

var colourData = colourList.Select(c => new SelectListItem()
{
Text = c.ColourName,
Value = c.ColourId.ToString(),

});

return Json(colourData, JsonRequestBehavior.AllowGet);
}

 

Finally, we need to add the following jQuery handlers for the dropdownlist selection changed

<script type="text/javascript">
$(document).ready(function () {
$("#ddlCars").change(function () {
var idModel = $(this).val();
$.getJSON("/Home/LoadModelsByCar", { id: idModel },
function (carData) {
var select = $("#ddlModels");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Select a Model"
}));
$.each(carData, function (index, itemData) {

select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
$("#ddlModels").change(function () {
var idColour = $(this).val();
$.getJSON("/Home/LoadColoursByModel", { id: idColour },
function (modelData) {
var select = $("#ddlColours");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Select a Colour"
}));
$.each(modelData, function (index, itemData) {

select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
});

</script>

And then add the dropdowns for Model and Colour

<p>
@Html.DropDownListFor(Model => Model.Models, new SelectList(Enumerable.Empty<SelectListItem>(), "ModelId", "ModelName"),
"Select a Model", new { id = "ddlModels" })

</p>
<p>
@Html.DropDownListFor(Model => Model.Colours, new SelectList(Enumerable.Empty<SelectListItem>(), "ColourId", "ColourName"),
"Select a Colour", new { id = "ddlColours" })

</p>

And then, when we build and run we can get to choose the Car, Model and Make, a cascading dropdown built using jQuery and MVC 3

I have uploaded the Visual Studio 2010 Solution as well as the Scripts for the CascadeSample Database to https://skydrive.live.com/?cid=069f94a102eff49a&sc=documents&client=wnf&id=69F94A102EFF49A%21760#cid=069F94A102EFF49A&id=69F94A102EFF49A%21761&sc=documents

Feel free to download and use it for your projects Smile

Also, do share if you find better ways to implement the same.

Cheers!!

Print | posted on Tuesday, June 14, 2011 4:47 PM

Comments on this post

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
i love what you wrote. wish to get more , thanks
Left by designer clothes on Jun 25, 2011 2:38 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
This is really helpful for handling multiple dropdowns. Could you please help in getting more material?
Left by prads on Jun 26, 2011 11:20 AM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
please the attached project in this Demo is different from the about Demo,Can i get the link to the correct Project Samples
Left by onyekachic on Jun 30, 2011 11:40 AM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Thanks for you sharing, but i have a problem: Choose how to modify the data restore options?
--With Google Translate
Thanks again
Left by junxy on Jul 15, 2011 9:22 AM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
This is easily the clearest explanation of how to do this that I've read, and I've read about six different long-winded explanations that I couldn't get to work. But I was able to get this one to work. Thank you so much
Left by bob on Jul 26, 2011 10:27 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Best explanation I've seen.
Worked right out of the box and simple enough so that modification for my use is no problem.

Thanks
Left by phil on Jul 27, 2011 7:37 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Hello friend, it really is a good example is been looking for three days. You and your waterfall simple example, I have a happy life ..

thanks brother.
Left by elperucho on Aug 16, 2011 5:25 AM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
This is one is great Article to bind dropdownlist with selected list.i have also used this article into my project.
once again thanks .
Left by Pappu on Sep 10, 2011 2:55 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Thankx Brother for this good article.
Left by saurabh on Sep 16, 2011 6:27 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
This is the best example.
Thanks a ton. :)

but I have one question, How to retrieve back the value of selected dropdownlist to controller?

sorry if the question sounds inappropriate, I am just a newbie in ASP.Net MVC
Left by SVD on Oct 01, 2011 6:09 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Thanks for this, it's an excellent setup for what I wanted. I'm having trouble getting the values to persist across a new page load though (I have the combos in the header(partial view)). Any chance you could point me in the right direction on how to go about doing this please??
Left by Daryl on Oct 11, 2011 12:20 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
i have just used this article into my project, it fine work in IE and not in FireFox 7.0.1 . Can you help me

Thanks a lot
Left by vam on Oct 11, 2011 2:00 PM

# SHOWWW

Requesting Gravatar...
Muito bom!
Parabéns...
Salvou minha vida!!
Left by Bruno Bianchini on Nov 10, 2011 2:57 AM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
many thanks for a great piece of code
Left by rob koch on Nov 15, 2011 11:52 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
the artical is very good. its really works. thanks for
Left by gorav pratap on Nov 25, 2011 12:24 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Firstly let thank you for this great piece of code.
But I have a problem when I moved to my application when selecting the first item, the cascade dropdown is not updating. It looks like that when the change on the selecteitems is not working for the first item on the list. Can you please help me.
Thanks in advance.
Left by Miguel on Nov 29, 2011 3:56 AM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Please send solution

In what way i can display data in table according to selected item from dropdownlist...

Thanks In Advance
Left by rajeev on Dec 14, 2011 9:16 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Thank you. I looked for a long time for a simple example that shows how to do that and looked at af ew of them but this one is the best and clearest of all

Thank you
Left by Zeev on Dec 15, 2011 9:46 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Very nice and informative article that beautifully elaborate the basics of DropDownList Control in ASP.Net. Its really helpful for me. Thanks for sharing with us. I had found another nice post with wonderful explanation on DropDownList Control, for more details about this post you check out this url...

http://mindstick.com/Articles/c59ff82f-4d2c-4874-a868-9088381efa69/?DropDownList%20in%20ASP.Net

Thanks everyone for your precious post!!!
Left by Piyush Chandra on Jan 12, 2012 3:40 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Simply perfect! Thank you very much!
Left by Lucas Reis on Jan 13, 2012 6:09 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Life saver! You just solved my 6-8 hour problem. Greatest post ever.
Left by Daniel Chimento on Feb 13, 2012 12:54 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
thank you very much, you have solve my problem
Left by wsugiri on May 10, 2012 6:41 AM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Thank you so much for this tutorial, ti was very helpful and I've learned a lot.
Left by Jacob Glad on May 12, 2012 10:58 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Thanks for this post.........
I have another problem.
I need to get the values from one of my db tables plus some hard coded values into one dropdownlist.
can you help me in doing this?

Thanks a lot
Left by cnip on May 24, 2012 12:02 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Thank you! Implemented perfectly for me on my site in just minutes!
Left by kmw_denver on Jul 15, 2012 3:29 AM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Excellent work Boss.Really helpfull.
Left by Anand on Oct 05, 2012 11:38 AM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Nice article. But i cant use that because i dont have razor. I have some problems with my dropdown. Could u put again this one in MVC.
Thanks.
Left by Angelina Deisy on Oct 13, 2012 11:34 AM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
How do you implement the Cascading inside a JQuery UI Dialog?
Left by Rabah on Dec 05, 2012 11:55 PM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Nice piece of code. Working perfect using mvc3/razor.

Excelent idea by using Enumerable.Empty<SelectListItem>() to start the dropdown.

Thanks!
Left by Luis on Jan 03, 2013 4:49 AM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Excellent Article. Thanks for this, you saved my day.
Left by Pawan Nirvana on Apr 26, 2013 3:02 AM

# re: Cascading Dropdownlist in ASP.NET MVC 3 using jQuery

Requesting Gravatar...
Does it work in MVC4?
Left by Asif on Oct 18, 2013 1:00 AM

Your comment:

 (will show your gravatar)