In this post we will see how to implement a Cascading DropDownList in Blazor. When we talk about a Cascading DropDownList (or dependent DropDownList), we mean when the options of a DropDownList are filtered by another DropDownList.
For example, if we have the Country and State DropDownLists, then the States to be displayed will be filtered according to the selected Country.
In this video I show how to implement this step by step:
In this post I’ll summarize the content of the video:
Note: This code was done with ASP.NET Core 3.1.
For our example, what we did was to create the Country and State entities, and we added a StateId property in a Person class, because we want to cascade the DropDown in this entity:
Then, I create the tables corresponding to these entities in my database. We can also use Data Seeding to fill these entities with test data.
The next step is to place the DropDownLists in a form. However, at the time of writing this entry, the InputSelect component of Blazor does not support ints (integers) as a value, therefore, we have to create a component that does this. We can create it as a class, since we are only going to extend the InputSelect functionality to handle ints (I think this code was written by Steve Sanderson):
With this we can use the InputSelect with numbers. In this case we use “countryId” as a component field, because our EditForm model does not bring a Country property (we only put Status in the Person class). We also use ValueChanged to execute a method when the value of the Country DropDownList is changed. This way we will execute the State filter:
In the case of the State DropDownList, we do almost the same, except that since we do not need to use ValueChanged, we can simplify the code:
In the C # code of the component we implement the CountryHasChanged method, where we call the LoadStates method, which is responsible for carrying out the filter:
Finally, in the country controller we look for the list of countries and the states filtered by country:
These are the steps to implement a cascade DropDownList.
- With cascading DropDownLists we can filter the values of a DropDownList according to the values of another DropDownList
- We use the ValueChanged attribute to execute a functionality when the value of a component changes
- We create the InputSelectNumber component to make the InputSelect component handle integers.
If you want to learn step by step how to build Web Applications from Scratch using Blazor, check out my full course: https://www.udemy.com/course/programming-in-blazor-aspnet-core/?referralCode=8EFA9D9FF38E3065DF0C