There are several samples how to create cascading dropdown lists for ASP.NET MVC on the Web. But in my opinion they are overcomplicated. Manual generation of tags, JSON format to pass data from controller to view, using web services instead of usual action methods, all this is unnecessary.
I will show now how to obtain this.
At first the model. We will use a class Brand defined as:
The overriding of ToString() method allows us to do not explicitly pass dataValueField and dataTextField parameters to SelectList constructor in our views.
Class Repository which will support us with data has these two methods:
Car controller has two versions of Add action for GET and POST methods respectively:
The difference is only what a version for GET method does no validation. You can see what if input data passes validation brandName parameter is cleared and removed from ModelState dictionary to reset a dropdown list with brand names in the form. Of course in a real application new car object will be added to a database here.
Helper private methods are defined as:
And we need one more action method which will be called every time a value in the dropdown with brand names changes:
First part of a source of Add.cshtml is here:
Partial view ModelDropDownList looks like:
Both dropdown lists are of required CSS class, so jQuery validation plugin knows what user has to select some value in each of them.
It means what after page is loaded
1) client-side form validation will be started and
2) changing value in the brands dropdown list will lead to AJAX call which refreshes DIV containing models dropdown list with correct markup.
The result looks like: