Saturday, June 4, 2011

Cascading dropdownlist in MVC3 Razor

I was searching a cascading dropdownlist for MVC 3 Razor for my new project at work. Since I’m new to MVC 3 I searched for similar example in the Internet, but couldn’t find any example to fulfill my requirement. There were lots of similar example but most of them are not working or not compatible with Razor. Eventually I was able to come up with a working solution and one good example from the internet also helped me to develop this solution. I hope this will help you a lot.

Razor View

Controller

Most of the example I have seen in the internet, it returns IList type collection as a Json result from the controller. I think that is the main reason for most of the examples does not work. But what I have done here is, instead of sending IList collection as the Json result, I'm sending a SelectListItem collection. It's working fine and if you have any suggestion please do send me to improve this solution.

Also you can download complete source code here



9 comments:

Langdon said...

Gracias!! Me ha sido muy util!! Buen aporte!

Isuru Kottachchi said...

Wonderful work Hasi! Keep it up! Just one question; do you normally use ViewModels in your solutions? As far as I know, it is a better practice to use VMs than binding the model directly to the View - yet it is optional.

Rabah said...

Hi Hasi,
I really liked your approach. I am considering using it in my code. However, I am stumbling in one issue if you can help. Can you showing how to implement the same code but inserting it the Department View/Controller part and not in the View/Controller location part as you did.
Thanks
Rabah USA

Madhu said...

Hi Hasi,
I have doubt.
Whenever im using $.getJSON its shows error.
I used $.ajax but now its shows error that data is undefined..
Do u have any solution. Thanks ..

Madhu said...

Hi Hasi,
I have doubt.
Whenever im using $.getJSON its shows error.
I used $.ajax but now its shows error that data is undefined..
Do u have any solution. Thanks ..

Unknown said...

Hi Hasi,
how to Bind Cascading dropdown lists MVC3,Very useful article to me.

Thanks,
Vaiyapuri from TamilNadu

netman61270 said...

Ok, I get the content in the second dropdownlist, but if there is only one selection (e.g. there is nothing else to select) there is no default selection and the value from the second box is empty when I try to use it's value...

Biznes və Biz said...

Thanks Hasi...

Neha Rustagi said...

Thanks Hasi... This was really helpful