tags:

views:

3544

answers:

3

How do I create a ListBox in ASP.NET MVC with single selection mode?

+7  A: 

I am assuming you are looking for a select box visually like the ListBox, meaning with multiple rows displayed, but functionally like the DropDownList (allowing for only one selection).

It looks like there is not a particularly easy way to pull this off using ListBox. I'd suggest using Html.DropdownList, similar to this:

<%=

Html.DropDownList("list1", new Dictionary {{"size", "5"}} ) %>

The size attribute will give the select box the look of a ListBox. Also, you will need to change your ViewData item from MultiSelectList to SelectList.

Jeffrey Meyer
BTW the html spec says to use SIZE instead of ROWS. Maybe they both work I'm not sure.
Todd Smith
I think it needs to be new {size = 5}
Todd Smith
you are right. brain lapse -- kept thinking it was rows, looked it up as size, and wrote rows anyway. i'll edit my answer.
Jeffrey Meyer
A: 

the below should do it: The object is translated in a list of attributes for the select element.

Html.DropDownList("list1", new Object {@rows = 5, @multiple = false} )

NTulip
Even when you set multiple = false it still ends up as <select multiple>... in the resulting HTML.
Todd Smith
A: 

I found this link very helpful.

Vadim