In this article, I am explaining how to populate items in dropdownlist on the basis of another dropdownlist value. I am also using entity framework code first model to get the list of countries and its states.
· Open Visual Studio 2010
· Create a new ASP.Net MVC 3 or 4 web application and named it as CascadingDropDown for this application.
· Choose Razor as the View engine and click OK
· Add a Controller in your project and give name as HomeController.
· Create a model class in the Model folder as shown below:
In this model class I have created a property CountryID (hold selected value of country), State (hold selected value of state), Countries and States (hold list of available country and its states).
Add some sample data in database and intialize it when database has been created:
Add a connection string in the web.config file under the configuration tag:
Modify the Global.asax file as shown below:
Create a HomeController and add the following action methods. In this controller, Index action return a Model type object to Index view by holding the list of countries from the database. SelectCountry action return a list of state on the basis of country id.
Add an Index View and modify this as given below:
Add a _States partial view.
Now run an application. It will something look like below:
When javacsript is turned off a select button will also be display in the UI in order to populate the states.
When you select the country, it will populate all states in the state dropdown on the basis of selected country. You can see in the below screenshot.
Thanks for reading this article. You can enter your valuable comments and suggestion to improve this article in the comment box.
In order to get the source code of this application, you can also enter your emailid in the comment box.