Asp.net-Mvc-3

如何使用 DropdownList 幫助器正確創建 MultiSelect <select>?

  • December 7, 2011

(對不起,這裡有幾個項目,但似乎沒有一個能讓我完成這項工作。)

我想創建一個允許多項選擇的 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 =&gt; 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 作為與值匹配的字元串的集合、作為與此 ID 匹配的 Guid 的集合以及作為具有鍵和值的匿名類型以匹配 ViewBag 中的項目。似乎沒有任何效果。

DropDownListFor如果要創建多選列表,則不要使用。你使用ListBoxFor助手。

查看型號:

public class MyViewModel
{
   public string[] SelectedIds { get; set; }
   public IEnumerable&lt;SelectListItem&gt; 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 =&gt; new SelectListItem
       {
           Value = x.ToString(),
           Text = "item " + x
       })
   };
   return View(model);
}

看法:

@model MyViewModel
@Html.ListBoxFor(x =&gt; x.SelectedIds, Model.Items)

引用自:https://stackoverflow.com/questions/8422718