ListBox in asp net mvc
Sardar Mudassar Ali Khan
Posted on July 7, 2023
In ASP.NET MVC, there is no specific "ListBox" control like in traditional ASP.NET Web Forms. However, you can achieve similar functionality using HTML and Razor syntax within your views.
To create a ListBox-like control in ASP.NET MVC, you can use the <select>
HTML element with the multiple
attribute set to allow multiple selections. Here's an example of how you can create a ListBox in an ASP.NET MVC view:
@{
// Define a list of items
var items = new List<SelectListItem>
{
new SelectListItem { Value = "1", Text = "Item 1" },
new SelectListItem { Value = "2", Text = "Item 2" },
new SelectListItem { Value = "3", Text = "Item 3" }
};
// Retrieve selected values
var selectedValues = new[] { "2", "3" }; // Example selected values
}
@Html.ListBox("selectedItems", items, new { @multiple = "multiple", @class = "form-control" })
In this example, we define a list of SelectListItem
objects representing the items in the ListBox. We also define an array of selected values for pre-selecting some items.
The Html.ListBox
helper method is used to render the <select>
element. The first parameter is the name of the ListBox control (selectedItems
in this case). The second parameter is the list of SelectListItem
objects, and the third parameter is an anonymous object used to specify additional attributes for the <select>
element.
The @multiple = "multiple"
attribute allows multiple selections in the ListBox. The @class = "form-control"
attribute is optional and can be used to apply CSS classes for styling purposes.
When the form is submitted, the selected values from the ListBox will be bound to a corresponding property in your model or controller action method. For example, you can have a property named SelectedItems
in your model or method parameter to capture the selected values.
Note: This is just a basic example, and you can customize it further based on your specific requirements.
Posted on July 7, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.