1

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

2 Answers 2

4

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.

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

Comments

3

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.

Comments

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.