I am interested in how to implement cascading dropdown lists for addresses in a Razor view. My Site entity has a SuburbId property. Suburb has a CityId, and City has ProvinceId. I would like to display dropdowns for all of Suburb, City, and Province on the Site view, where e.g. the suburb dropdown will initially display "First select a City", and the City dropdown, "First select a province". On selecting a province, cities in the province are populated etc.
How can I achieve this? Where do I start?
be aware, that this solution doesn't work directly with EF 4.0. It causes "A circular reference was detected while serializing..." error. Here are possible solutions http://blogs.telerik.com/atanaskorchev/posts/10-01-25/resolving_circular_references_when_binding_the_mvc_grid.aspx , I've used second one.
Let's illustrate with an example. As always start with a model:
Next a controller:
And finally a view:
As an improvement the javascript code could be shortened by writing a jquery plugin to avoid duplicating some parts.
UPDATE:
And talking about a plugin you could have something among the lines:
And then simply wire it up:
To implement cascading drop down lists that support MVC's built in validation and binding, you will need to do something a little different than what is done in the other answers here.
If your model has validation, this will support it. An excerpt from a model with validation:
In your controller you need to add a get method, so that your view will be able to get the relevant data later:
Now, to the View that I mentioned earlier:
In your view you have two drop downs similar to this:
The content in the drop downs are bound by the controller, and are automatically populated. Note: in my experience removing this binding and relying on java script to populate the drop downs make you lose validation. Besides, the way we are binding here plays nice with validation, so there is no reason to change it.
Now onto our jQuery plugin:
You can copy the above jQuery that i created, into
<script>...</script>
tags in your view, or in a separate script file if you wish (note I updated this to make it cross browser, however the scenario in which i was using is no longer required, it should work however).In those same script tags, (not in a separate file) you can call the plugin by using the following javascript:
Remember to add the
$(document).ready
part, the page must be fully loaded before you try to make the drop downs cascade.Thanks Darin for your lead to the solution. It greatly helped me to arrive to the point. But as 'xxviktor' mentioned, I did got circular ref. error. To get rid of it, I've done this way.
And to achieve auto cascading, I've slightly extended jQuery extension this way.
And the actual JS is using this parameter as below (inside JSON request).
Hope this helps someone with similar issue.
From controller I am getting the values