asp.net-mvc-3 – 如何使用DropdownList助手正确创建MultiSelect?

(对不起,这里有几个项目,但没有一个似乎允许我得到这个工作。)

我想创建一个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和作为匿名类型与键和值以匹配ViewBag中的项目。没有什么似乎工作。

解决方法

如果要创建多选列表,则不要使用DropDownListFor。你使用ListBoxFor帮助器。

查看型号:

public class Myviewmodel
{
    public string[] SelectedIds { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

控制器:

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

视图:

@model Myviewmodel
@Html.ListBoxFor(x => x.SelectedIds,Model.Items)

相关文章

一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....
推荐一款比较牛的富文本编辑器:http://kindeditor.net/
一、异或运算异或,英文为exclusive OR,或缩写成xor异或(x...
一、云计算概念 云计算(cloud computing)是基于互联网的相...