How to add an Option label on ListBoxFor HTML Helper in ASP.Net MVC

2.6k views Asked by At

How can I add an option label like the one existent on the DropDownListFor for a ListBoxFor HTML Helper ?

I have the code similar to bellow:

<%= Html.ListBoxFor( m => m.SelectedElements, new MultiSelectList(Model.AllPossibleElements, "ID", "Text")) %>

And the image bellow is the output:

enter image description here

I would like to have a default selection (option label) like: "Please, select the value".

2

There are 2 answers

1
Erik Funkenbusch On BEST ANSWER

The reason that Html.DropDownListFor() has an "option" parameter is that dropdown lists, when they don't have a selected value, are blank and you can't see their contents without expanding them.

Listboxes, typically do display their contents, and thus an option is not necessary. An unselected listbox doesn't need something to say "Select an option" because the options are clearly visible.

I think your problem here is that you're using a third party library to re-style a listbox to look like a dropdownlist, and thus it's not behaving the way you would expect a dropdownlist to behave (because it's not a dropdownlist, it's a listbox that just looks like dropdownlist).

The Listboxfor helper doesn't provide this, because it doesn't typically make sense to provide it. All that the option is doing is creating an entry that is first in the list that has an empty value. Thus, when the form is submitted, the empty value will trigger any required validation you may have on the backing property.

So, to do this yourself, you need to add an empty item with just the text you want, and an empty value.

1
reggaemahn On

You can do @Html.LabelFor(x => x.ListBoxName, "Your Label");

Where ListBoxName is the name of your ListBox in your ViewModel.

Update: Sorry, I thought you wanted an HTML label. What you're looking for is a placeholder.

<%= Html.ListBoxFor( m => m.SelectedElements, new MultiSelectList(Model.AllPossibleElements, "ID", "Text"), new { @placeholder = "Your Label" }) %>

Note: This doesn't actually create an 'option' inside the ListBox. So, there might be compatibility issues with older browsers.