Dynamic DropDownLists allows the user to select an item from the first dropdownlist which populates the second dropdownlist based on the selection of the first dropdownlist. In this article we are going to demonstrate how to implement dynamic dropdowns using ASP.NET MVC 3 framework.
Creating the ViewModel:
The first step is to create a ViewModel which will represents the elements on the View. Our ViewModel revolves around the relationship between the category and products. The user will select a category from a dropdownlist which will populate all the corresponding products in another dropdownlist. The implementation bellows shows the ArticleEditViewModel:
As, you can see that to keep the demo simple we have hard-coded the categories. In the next section we will demonstrate how to populate the categories dropdownlist using the ArticleEditViewModel.
Populating Categories DropDownList:
The Index action of the HomeController returns the new ArticleEditViewModel to the view. The view uses the Categories property of the ArticleEditViewModel to populate the dropdownlist. The Index action is shown below:
The DropDownList is populated using the code below:
The DropDownList is bind to the SelectedCategory property of the ViewModel. The SelectedCategory property is also decorated with the [Required] attribute which makes sure that the SelectedCategory is not left blank or on the default item. The screenshot below shows the validation being fired when the Categories DropDownlist is left at the default option and the view is submitted.
The validation is fired because the default option "Select a category" does not have any value associated with it. ASP.NET MVC framework tries to bind the empty string with the SelectedCategory property but fails since the SelectedCategory is marked with [Required] attribute.
Fetching the Products and Populating the Dependent DropDownList:
Our next task is to get the selected category and then fetch the associated products using the categoryId. This will be performed by an ajax call using our beloved jQuery library. The implementation below shows the details.
The code above calls the GetProductsForCategory action with the categoryId as the input parameter. The GetProductsForCategory returns the JSON response which represents the products. Before populating the DropDownList with the products we clear all the items in the DropDownList. The GetProductsForCategory action is implemented below:
The above action simply returns the hard-coded values but in actual application you will retrieve the products from a data storage system.
The screenshot below shows the final result:
Conclusion:
In this article we learned how to make dynamic dropdownlist in the ASP.NET MVC framework. In the future article we will demonstrate how to simplify this approach by creating an HtmlHelper for Dynamic DropDownLists.