In this post we will create a Blazor component to be able to select several options in a form. An example would be if we have a form for entering movie data, and we want to be able to select movie genres (action, drama, comedy, etc.) from a list of genres. We can do this with our component.
Step by Step Video
Summary of the Video
Our component will consist mainly of two columns: In the left column you will find the elements that are not selected, and in the right column are the selected elements. We will also have buttons to select and deselect everything.
At the code level, the component will consist of two lists, selected items and non-selected items. The selection and deselection operations will consist of moving elements from one list to another.
In the end, our component will consist of about 50 lines of code:
We can see that we have UI with two lists, and that a method is executed when we click on a list item. This to select or deselect the element, as appropriate.
As I mentioned, the selection and deselection operations consist of moving an item from one list to another. For example, to select an item, we move it from the NoSelected list and to the Selected list:
We use a ViewModel (POCO, or Plain Old CLR Object) data type of an individual item. This allows us to have flexibility in implementing new functionalities in our component. For example, if we wanted to add a property that prevents the user from selecting an item, we could place it in that ViewModel:
Finally, to use our component,we can place it in a form, passing the selected and non-selected elements. In the course, in the context of a movie form, we do the following:
This component handles movie creation and calls a component that contains a movie form:
And in the MovieForm component we do the following (summary with only the relevant parts):
- We can use Blazor to create interactive applications with C#
- With the MultipleSelector component we can allow the user to select several elements from a list
This tutorial comes from my Udemy course, where we created an application from scratch with Blazor. Learn how to create your own applications today and publish them with Azure DevOps today!