Friday, February 11, 2011

Degradable cascading dropdown lists

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.

At the same time it's important what users with disabled Javascript could still use cascading dropdown lists on your form.

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:


Now a view markup. Of course we need to add a reference to jquery.validate.min.js script in _Layout.cshtml file where references to other Javascript and CSS files are.

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.

And last but not least, Add.cshtml contains this Javascript code (this is promised second part of a source):


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.

If Javascript is disabled in user's browser it's still possible to select another brand, press submit button, and corresponding models will be rendered on the form.

The result looks like:

No comments:

Post a Comment