我几乎已经解决了这个问题,但需要一点插入。
这是我所拥有的:
在数据库中,我有一个名为 active 的字段,它是一个位字段(True/False)
我在 View 表单上放置了一个下拉列表,如下所示:
<%= Html.DropDownList("lstActive", new SelectList((IEnumerable)ViewData["ActiveList"])) %>
在我的 Controller 中,我只需使用这段代码在下拉列表中生成 True/False:
List<string> activeList = new List<string>();
activeList.Add("True");
activeList.Add("False");
ViewData["ActiveList"] = new SelectList(activeList);
我想绑定(bind)到数据库中名为 active 的字段并在下拉列表中选择它。当我这样查看时,我得到了:
alt text http://rjmueller.net/sitesimages/temp/dropdown.gif
所以问题是:
显然我没有指向 Value 和 Text 属性,但在这种情况下是什么? 我如何选择数据库中的值?
如有任何帮助,我们将不胜感激。
最佳答案
首先,这可能更适合单选按钮,而不是选择。其次,您确实应该拥有一个属性为 IEnumerable<SelectListItem>
的 View 模型。为选择提供值。您可以直接在模型中构建它。
var model = new ViewModel();
model.ActiveList = new List<SelectListItem>
{
new SelectListItem { Text = "Yes", Value = "true" },
new SelectListITem { Text = "No", Value = "false" }
};
model.Active = false; // this will be the default
return View( model );
然后在您的 View 中(针对您的 View 模型类型进行强类型化):
<%= Html.DropDownListFor( m => m.Active, Model.ActiveList ) %>
使用单选按钮,您可以省略列表(因为只有两个选择)。
<%= Html.RadioButtonFor( m => m.Active, true ) %> Yes
<%= Html.RadioButtonFor( m => m.Active, false ) %> No
关于c# - 尝试在 MVC 中设置下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3041862/