Pass the Selected Values of the ListBox to Controller in ASP.NET Core
This blog explains how to send selected values of ListBox to ASP.NET Core Controller. Let's look at this with an example.
The following is the SampleViewModel class. It has two properties, Movies, and SelectedMovies. The property called Movies will bind the list of movies in the ListBox and the selected movie property will send the selected value from the view to the controller.
SampleViewModel.csThe following is a controller code. Microsoft.AspNetCore.Mvc.Rendering namespace is included to use SelectListItem.
The list of movies is assigned to the MoviesList variable. That MoviesList is assigned to the Movies property in the SampleViewModel. Finally, SampleViewModel is sent to view.
In the Result action method, the selected list is retrieved from the view and sent to the Result view to display the selected values on the page.
HomeController.csBelow is a view code. Here in the select tag helper size value is assigned as 5. Thus the list box will show 5 results. If the list box has a value of more than 5, a vertical scroll bar will appear and the user can view the values by moving the scroll bar.
Due to the 'multiple' attribute set, this allows multiple values to be selected. So on the webpage, it will provide a Listbox instead of a drop-down list.
Model.Movies property is assigned to the asp-items attribute, that will bind the list of movies to the list box. The SelectedMovies is assigned to asp-for, so it provides the controller with an array of movie IDs when submitting the form.
Index.cshtmlThe final one is the result view. The selected movie names are received by the integer array and displayed using the for-loop.
Result.cshtmlThe image below is the output of the code above.
I hope this article will be helpful to you. Keep coding
Related Article
Pass the Selected Values of the ListBox from View to Controller in ASP.NET Core Using jQuery Ajax
Comments
Post a Comment