Reputation: 4892
I am using latest MVC5. I want to use a ListBox NOT a DropDown. The decision which control to use is not single/multiple selection decision.
Thats the error I get:
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code
Additional information: The parameter 'expression' must evaluate to an IEnumerable when multiple selection is allowed.
@using (Html.BeginForm())
{
// @Html.ValidationMessageFor(model => model.)
@Html.ListBoxFor(x => x.SelectedCompanyId, new SelectList(Model.Companies, "CompanyId", "Address"), new { @id = "CompanyListBox" })
}
But how can I remove the multiple selection? jQuery does not help here as the razor exception is first raised before the document is ready:
$(document).ready(function () {
debugger;
$("#CompanyListBox").removeAttr('multiple');
});
Upvotes: 1
Views: 9603
Reputation: 1039438
You can only use the ListBoxFor
helper with IEnumerable<T>
properties. In your example, if SelectedCompanyId
is not an IEnumerable<T>
it simply won't work. The ListBoxFor
helper is designed to be used for multiple selections. Also if you remove the multiple="multiple"
attribute using javascript, it's the same as if you were using a DropDownListFor
helper.
Upvotes: 3
Reputation: 882
One way is to use a DropDownListFor and set the "size" attribute to be the number of visible items you want.
For example
@Html.DropdownListFor(x => x.SelectedCompanyId, new SelectList(Model.Companies, "CompanyId", "Address"), new { @id = "CompanyListBox", @size=10 })
Will display a "listbox" with 10 visible items.
Upvotes: 4