2014-03-30 47 views
1

我正在使用最新的MVC5。 我想使用ListBox而不是DropDown。控制使用的決定不是單一/多重選擇決定。ListBoxFor在asp.net中單擊選擇mvc

那是錯誤,我得到:

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

但我怎麼能刪除多重選擇? jQuery的不幫助這裏的剃鬚刀例外首次提出之前準備好文檔:

$(document).ready(function() { 
    debugger; 
    $("#CompanyListBox").removeAttr('multiple'); 
}); 

回答

2

一種方法是使用DropDownListFor並將「size」屬性設置爲所需可見項的數量。

例如

@Html.DropdownListFor(x => x.SelectedCompanyId, new SelectList(Model.Companies, "CompanyId", "Address"), new { @id = "CompanyListBox", @size=10 }) 

會顯示 「列表框」 用10個可見項。

+0

工作感謝! – HelloWorld

2

您只能使用ListBoxFor傭工IEnumerable<T>性能。在你的例子中,如果SelectedCompanyId不是IEnumerable<T>,它根本行不通。幫助器ListBoxFor旨在用於多種選擇。另外,如果您使用javascript刪除multiple="multiple"屬性,則與使用助手的DropDownListFor相同。