29

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

1

5 Answers 5

36

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<string, object> {{"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.

Sign up to request clarification or add additional context in comments.

3 Comments

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

MVC5.cshtml

@Html.DropDownList("PropertyID", null, htmlAttributes: new {size=5, @class="form-control" })

Controller

ViewBag.PropertyID = new SelectList(db.EntityItems);

Comments

3

The best solution is here.

<script type="text/javascript">
    $(document).ready(function () {
        $('select').removeAttr('multiple');
    });
</script>

Comments

2

Following Code Works for me,

<%=Html.DropDownList("list1", lstItem, new {@size = 5})%> where lstItem represents the List of SelectListItem

Comments

-2

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} )

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.