« Greenhouse and Energy Reporting NGERS | Main | Manifesto for Agile Software Development »
Sunday
May312009

ASP.NET MVC Cascading DropDownLists

Creating DropDownLists using WebForms is easy enough, for those who are venturing into the the world of MVC this may not be as straight forward.

I’ll be using the classic scenario of Cars and their related makes and models.

CarController.cs

public class CarFormViewModel
{
MakeModelRepository makeModelRepository =
    new MakeModelRepository();

private string _carMake = "";

public Car Car { get; private set; }
public SelectList CarMakes { get; private set; }
public SelectList CarModels { get; private set; }
public string CarMake
{
get { return _carMake; }
set { _carMake = value; }
}

// Constructor
public CarFormViewModel(Car car)
{
Car = car;
CarMakes = new SelectList(makeModelRepository.
        GetCarMakes(), "Value", "Text");

if (car.CarMakeModelId > 0)
CarMake = car.CarMakeModel.CarMake;

CarModels = new SelectList(makeModelRepository.
        GetCarModels(CarMake), "Value", "Text", Car.CarMakeModelId);
}
}

Something to be aware of is the use of valueSelected when defining your SelectList, make sure your view items e.g. DropDownList names match your database field names. I found the selected value was not being set correctly when editing a records.

CarForm.aspx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl
<Vehicles.Controllers.CarFormViewModel>" %>

<script type="text/javascript">
$(function() {
$("#CarMake").change(function() {
var carMake = $("#CarMake > option:selected").attr("value");
var urlAction = "<%= Url.Action("FindCarModels", "Car") %>";
$.getJSON(urlAction, { carMake: carMake }, function(data) {
$("#CarMakeModelId").addItems(data);
});
});
});
</script>

<%= Html.ValidationSummary("Edit was unsuccessful. Please correct
the errors and try again.") %>
<%
using (Html.BeginForm())
{%>
<fieldset>
<
legend>Car</legend>
<
p>
<
label for="CarMake">
Make:</label>
<%= Html.DropDownList("CarMake", Model.CarMakes) %>
<%= Html.ValidationMessage("CarMake", "*") %>
</p>
<
p>
<
label for="CarMakeModelId">
Model:</label>
<%= Html.DropDownList("CarMakeModelId", Model.CarModels) %>
<%= Html.ValidationMessage("CarMakeModelId", "*") %>
</p>
<
p>
<
input type="submit" value="Save" />
</
p>
</
fieldset>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>

Make sure to change the inherits property to reference your new ViewModel. Note the use of the Url.Action helper, this little snippet helps you creates the correct path to your controller action without the use of those dots e.g. …/<controller>/<action>/

jHelper.js

Borrowed from Steve Michelotti.

$.fn.clearSelect = function() {
return this.each(function() {
if (this.tagName == 'SELECT')
this.options.length = 0;
});
}

$.fn.addItems = function(data) {
return this.clearSelect().each(function() {
if (this.tagName == 'SELECT') {
var dropdownList = this;
$.each(data, function(index, optionData) {
var option = new Option(optionData.Text,
                         optionData.Value);

if ($.browser.msie) {
dropdownList.add(option);
}
else {
dropdownList.add(option, null);
}
});
}
});
}

Little helper that clears and adds items to DropDownLists.

Something I found frustrating is when in debug mode a script reference would work find but when running using IIS the script would not load correctly. What you had to do was use those good old dots to get it loading correctly. My tip is to use the ResovleUrl helper.

<script src="<%= ResolveUrl("~/Scripts/jquery-1.3.1.js") %>" 
type="text/javascript"></script>

<
script src="<%= ResolveUrl("~/Scripts/jHelper.js") %>"
type="text/javascript"></script>

There are some workarounds I’ve seen that don’t break intellisense but look a bit messy. I figure I’ve lived without it for this long.

Here is the source code, if there is anything that is unclear or you have any questions feel free to email me.

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments (30)

Thanks for posting the source.

June 1, 2009 | Unregistered Commentergkochanowsky

Big thanks.

August 5, 2009 | Unregistered CommenterMatt

I would like to thank you for the efforts you have made in writing this article. I mostly agree with you most of the point I have subscribed the feed and looking forward for the followup subscriptions

September 11, 2009 | Unregistered Commenterplumber paddington

Thanks for posting this - I've been wondering whether it'd be possible to use BE.Net as a CMS, glad you got it cracked. I'd be really interested in the code changes that you needed to make to get this running - any chance of posting your changes and/or a download? Pretty please?! ;)

February 4, 2010 | Unregistered Commenterexterminator

I am trying to get your dropdown solution to work in 2010 .Net 4.0. Everything seems fine and fires, but when the data returns from the FindCarModels action nothing happens. The data is correct , but the logic does not execute where I have the alert(Sweet 3) ? Do you have any ideas ?

$(function() {
$("#CarMake").change(function()
{

var carMake = $("#CarMake > option:selected").attr("value");
var urlAction = "<%= Url.Action("FindCarModels", "Wizard") %>";

alert('Sweet : ' + carMake);

$.getJSON(
urlAction,
{ carMake: carMake },
function(data)
{
alert('Sweet3');
$("#CarMakeModelId").addItems(data);
});
});
});

February 18, 2010 | Unregistered CommenterDuncan.Net

Found the Answer to the above. A change to MVC 2 JSONResult defaults. See http://www.davidhayden.me/2009/11/jsonresult-and-jsonrequestbehavior-in-aspnet-mvc-2.html

February 18, 2010 | Unregistered CommenterDuncan.Net

Thanks for posting this - I've been wondering whether it'd be possible to use BE.Net as a CMS, glad you got it cracked. I'd be really interested in the code changes that you needed to make to get this running - any chance of posting your changes and/or a download? Pretty please?! ;)
Inbound Links

August 7, 2010 | Unregistered Commenterlaura

Mr. Smith obtained a trademark for the term ugg boots
-and it is believed that he also obtained variations on the spelling-such as Ugg and Ugh. In 1995, Mr. Smith sold all rights of ugg
Holding to a Californian company by the name of Deckers Outdoor Corporation. Upon the purchase, Deckers acquired the uggs
trademark name for 24 countries and began utilizing the name of ugg ultra tall boots
-Australia.

August 12, 2010 | Unregistered Commentersunugg

gucci handbags, gucci bags, gucci handbag, gucci wallet, sunglasses gucci, coach outlet, coach handbags, coach bags, coach purses, coach wallet, fendi bags, fendi handbags, hermes bag, hermes handbags, hermes birkin, burberry outlet, burberry bags, burberry handbags, burberry scarf, chanel purses, chanel bags, chanel handbags, chanel sunglasses, chanel handbags, louis vuitton outlet, louis vuitton bags, louis vuitton handbags, louis vuitton wallet, louis vuitton purses, louis vuitton handbags, yves saint laurent, ray ban sunglasses, ray ban wayfarer, ray ban aviator, ray ban sunglasses, tiffany jewelry, tiffany and co, tiffany and company, tiffany engagement rings, tiffany necklace, mac cosmetics, mac cosmetics canada, mac pro, mac cosmetics outlet, balenciaga handbags, prada handbags, nike air max, air max 95, nike air max, air max 1, nike shox nz, nike shox r4, nike shox shoes, air yeezy, adidas shoes, adidas women shoes, dc shoes, gucci shoes, gucci shoes for men, gucci sneakers, lacoste shoes, puma shoes, mbt shoes, prada shoes, timberland shoes, ed hardy shoes, tiffany bracelet, supra shoes, d&g shoes, christian audigier, mbt women's shoes, new balance, adidas jacket, affliction clothing, affliction shirts, ed hardy clothing, ralph lauren polo, polo ralph lauren, abercrombie and fitch, abercrombie shirts, abercrombie jeans, lacoste polo, manolo blahnik, giuseppe zanotti, Alexander Mcqueen, Gianmarco Lorenzi, vibram five fingers, christian louboutin, christian louboutins, christian louboutin sale, nike air force one, nike outlet, nike basketball shoes, nike tennis shoes, nike sneakers, jordans shoes, nike sb dunks, nfl jersey, nfl jerseys, ed hardy jeans, ed hardy women's clothing, ed hardy swimwear, ed hardy bikini, ed hardy t shirts, p90x, p90x workout, p90x results, p90x reviews, spyder jackets, canada goose, north face jacket, north face, jimmy choo shoes, jimmy shoe, armani jeans, boss jeans, calvin klein jeans, diesel jeans, dsquared jeans, jack & jones, levis jeans, lee jeans, ed hardy jeans, true religion jeans, ugg classic short, ugg boots sale, fake uggs, fake uggs, ugg shoes, ugg boots, ugg cardy, ugg bailey button, cheap ugg boots, uggs outlet, ugg boots, ugg boots women, ugg classic tall, ugg classic tall, ugg classic short, ugg classic cardy boot, discount ugg boots, ugg boots on sale, cheap ugg boots, ghd flat iron, ghd irons, ghd iv styler, ghd styler, pink ghd, plancha ghd, ghd mk4, ghd hair straighteners, ghd hair straightener, hair straighteners ghd, ghd purple, christian louboutin pumps, cheap mens jeans, winter jackets, designer handbags, designer bags, designer purses, pumps women's shoes, cheap bags, ghd australia, purple ghds, uggs australia, ugg uk, discount ugg boots, womens uggs, ugg australia women's classic short boots, uggs for sale, ralph lauren polos, abercrombie and fitch outlet, lacoste wholesale, alexander mqueen, nike outlet online, jersey mlb, the north face jacket, diesel jean, true religion sale, dc skate shoes, timberland outlet, d g shoes, gucci bags on sale, coach outlet store, hermes bag, lv handbags, saint laurent, ray ban wayfarer sunglasses, ray ban polarized, prada handbag, wow addon, wow addons, wow addons, blu ray software, christian louboutin shoes, christian louboutin sale, christian louboutin boots, Christian Louboutin Pumps, christian louboutin sale , mbt shoes, mbt womens shoes, mbt shoes clearance, mbt shoes sale

August 12, 2010 | Unregistered Commenterair-max

For the help please use http://www.google.com

September 9, 2010 | Unregistered CommenterSomoscinc

This will accumulate your affluence Bell Ross in the best action possible, and will aswell ensure that they angle the analysis of time!Your Bell Ross Watches ability abiding yachtmaster dejected punch 116689 Replica Bell Ross will endure abundant longer, and will be in abundant bigger condition, if you analyze it to your car. You wouldn't let your Replica Bell Ross Watches get damaged and leave it, or leave it afterwards application it regualry and accepting the MOT. 马文鑫测试

September 21, 2010 | Unregistered CommenterBell Ross

The replica watches is known all over the world due to the high standards and excellent quality control. These top quality fake watches provide excellent performance,

September 24, 2010 | Unregistered Commenterfdsaf

we arechristian louboutin discount. In our websitewww.iclshoes.comyou can have more choices, such as
discount christian louboutin
Jimmy Choo shoes
Jimmy Choo Sandals
Jimmy shoes
christian louboutin sandals
Christian Sandals
Louboutin Sandals
Many people like to imitate the characters in the movie, especially super heroes wear.there are a variety of products such as:
lolita dress
spiderman costume
superhero costumes
black zentai
gold zentai
gothic lolita dress
And, we also provide fashion bags, such as:
Bridal Gowns
bridesmaids dresses
cocktail dresses

October 8, 2010 | Unregistered Commenterjimmy choo shoes

This season, the coach bags outlet series of more originality adornment to makeup dot, Women especially cannot seem to live without coach bags. They can usually come about throughout one thing to go within of them, plus they like it that way. Some ladies even take advantage of bigger instructor Handbags to serve as diaper coach online
for their tiny ones. Moreover the branded types also provide a broad variety of styles, brilliant colours as well as decent means in producing their Coach Handbags Replica like the handbags and purses. But coach outlet still gets huge lines outside of their stores at Christmas time and is one of the most sought after brands of any purse on the planet.

December 23, 2010 | Unregistered Commentercoach bags

This season, the coach bags outlet series of more originality adornment to makeup dot, Women especially cannot seem to live without coach bags. They can usually come about throughout one thing to go within of them, plus they like it that way. Some ladies even take advantage of bigger instructor Handbags to serve as diaper coach online
for their tiny ones. Moreover the branded types also provide a broad variety of styles, brilliant colours as well as decent means in producing their Coach Handbags Replica like the handbags and purses. But coach outlet still gets huge lines outside of their stores at Christmas time and is one of the most sought after brands of any purse on the planet.

December 24, 2010 | Unregistered Commentercoach bags

This site is dedicated to providing you with the best 3D TV related information, guides and news. Feel free to browse through our 3D TV list below, as well as our informative 3D TV guides and articles to learn more about this new and exciting display technology. We will also be reviewing the latest 3D Televisions to help you choose the best 3D TV for your home.
Be sure to read our comprehensive 3D TV guides listed below to help you learn everything you need to know to buy the best 3D TV for your home. Learn about the best plasma and LCD 3D TVs and the advantages of each technology so you can see through the manufacturer's hype and save money while buying the best available 3D TV for your home.

January 14, 2011 | Unregistered Commenterovencelet

Ugg boot is a legendary brand, you can't understand why it has a ugly and cunbersome appearance when you have first glimpse of her.But it has been a popular boot in the Eurasian land, now popoular wind blowing all over the world today.The guide of this wind is Euramerian stars.

March 16, 2011 | Unregistered Commenterlouis vuitton

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>