Pil*_*Bob 28 selectlist multi-select asp.net-mvc-3 drop-down-menu html.listboxfor
(对不起,这里有几个项目,但似乎没有一个允许我让这个工作.)
我想创建一个允许多选的DropDownList.我能够填充列表,但我无法获得当前选定的值似乎工作.
我的控制器中有以下内容:
ViewBag.PropertyGroups = from g in db.eFinGroups
where g.GroupType.Contents == "P"
select new
{
Key = g.Key,
Value = g.Description,
Selected = true
};
ViewBag.SelectedPropertyGroups = from g in company.Entities
.First().Properties.First().PropertyGroups
select new {
g.eFinGroup.Key,
Value = g.eFinGroup.Description };
在视图中我有:
@Html.DropDownListFor(model => model.PropertyGroupsX,
new MultiSelectList(ViewBag.PropertyGroups
, "Key", "Value"
, ViewBag.SelectedPropertyGroups),
new { @class = "chzn-select", data_placeholder = "Choose a Property Group", multiple = "multiple", style = "width:350px;" })
PropertyGroupX是模型中的字符串[].
我已尝试使用所选属性的所有类型的迭代...只传递值,只传递键,两者等.
另外,PropertyGroupX应该是什么类型的?字符串数组是否正确?或者它应该是包含当前属性组的字典?我真的很难找到这方面的文档.
有人建议我应该使用ListBoxFor.我已经改变了,仍然有同样的问题.呈现选项标记时,所选值未设置为选中状态.这是我尝试过的:
@ Html.ListBoxFor(model => model.PropertyGroups,new MultiSelectList(ViewBag.PropertyGroups,"Key","Value"))
我已经尝试将model.PropertyGroups作为匹配值的字符串集合,作为Guid的集合匹配此ID,并作为匿名类型同时具有Key和Value以匹配ViewBag中的项目.似乎没什么用.
Dar*_*rov 55
DropDownListFor如果要创建多选列表,则不使用.你使用ListBoxFor帮手.
查看型号:
public class MyViewModel
{
public string[] SelectedIds { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器:
public ActionResult Index()
{
var model = new MyViewModel
{
// preselect the first and the third item given their ids
SelectedIds = new[] { "1", "3" },
// fetch the items from some data source
Items = Enumerable.Range(1, 5).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = "item " + x
})
};
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
视图:
@model MyViewModel
@Html.ListBoxFor(x => x.SelectedIds, Model.Items)
Run Code Online (Sandbox Code Playgroud)