如何在ASP.NET MVC中使用单选模式创建ListBox?

Tod*_*ith 29 asp.net-mvc

如何在ASP.NET MVC中使用单选模式创建ListBox?

Jef*_*yer 36

我假设你正在寻找一个像ListBox一样的选择框,意味着显示多行,但功能上像DropDownList(只允许一个选择).

看起来没有一种特别简单的方法可以使用ListBox来解决这个问题.我建议使用Html.DropdownList,类似于:

<%= Html.DropDownList("list1", 
    new Dictionary<string, object> {{"size", "5"}} ) %>
Run Code Online (Sandbox Code Playgroud)

size属性将为选择框提供ListBox的外观.此外,您需要将ViewData项从MultiSelectList更改为SelectList.

  • 我认为它需要是新的{size = 5} (2认同)

小智 5

MVC5.cshtml

@Html.DropDownList("PropertyID", null, htmlAttributes: new {size=5, @class="form-control" })
Run Code Online (Sandbox Code Playgroud)

控制者

ViewBag.PropertyID = new SelectList(db.EntityItems);
Run Code Online (Sandbox Code Playgroud)