asp.net-mvc 如何使用单选模式在 ASP.NET MVC 中创建 ListBox?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/351483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I create a ListBox in ASP.NET MVC with single selection mode?
提问by Todd Smith
How do I create a ListBox in ASP.NET MVC with single selection mode?
如何使用单选模式在 ASP.NET MVC 中创建 ListBox?
回答by Jeffrey Meyer
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).
我假设您正在寻找一个在视觉上类似于 ListBox 的选择框,这意味着显示多行,但在功能上类似于 DropDownList(仅允许一个选择)。
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:
使用 ListBox 似乎没有特别简单的方法来实现这一点。我建议使用 Html.DropdownList,类似于:
<%= 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.
size 属性将使选择框具有 ListBox 的外观。此外,您需要将 ViewData 项从 MultiSelectList 更改为 SelectList。
回答by Ferrell Carr
MVC5.cshtml
MVC5.cshtml
@Html.DropDownList("PropertyID", null, htmlAttributes: new {size=5, @class="form-control" })
Controller
控制器
ViewBag.PropertyID = new SelectList(db.EntityItems);
回答by Developer
The best solution is here.
最好的解决方案在这里。
<script type="text/javascript">
$(document).ready(function () {
$('select').removeAttr('multiple');
});
</script>
回答by Chandra Prakash
Following Code Works for me,
以下代码对我有用,
<%=Html.DropDownList("list1", lstItem, new {@size = 5})%> where lstItem represents the List of SelectListItem
<%=Html.DropDownList("list1", lstItem, new {@size = 5})%> 其中 lstItem 代表 SelectListItem 的 List
回答by IEnumerator
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} )
Html.DropDownList("list1", new Object {@rows = 5, @multiple = false} )

