2016-03-28 29 views
0

我有一個下拉列表,您可以在其中選擇多個選項。 enter image description hereC#是否可以模擬綁定多個選項?

此下拉的代碼是: enter image description here

我怎樣才能在C#綁定多個「Devices」的,這樣,當該下拉加載 模型綁定將自動選擇被傳遞到視圖中的所有選項?

+1

可能的[Html。DropdownListFor選擇的值沒有設置](http://stackoverflow.com/questions/19476530/html-dropdownlistfor-selected-value-not-being-set) –

回答

1

對於你的情況,你應該使用其他的輔助工作時 - @Html.ListBoxFor它應該產生select元素與multiple屬性。

//note that i use MaintanceDevices property 
@Html.ListBoxFor(x => x.MaintanceDevices, new SelectList(Model.Devises, "ID", "Description"), new { @class = "multiselect form-control"}) 

此外,不要在助手中設置id屬性。這是更好地在你的視圖模型創建另一個屬性:

public List<int> MaintanceDevices { get; set; } 

填充它的控制器和MVC自動生成正確的標記爲您select元素綁定在表單POST。

1

您的模型中的設備屬性應該是一個Ids列表(其中是一個簡單的類型,如int或字符串),而不是設備模型列表(因爲您在Helper中使用new SelectList(Model.Devices, "ID", "Description"),所以我看到Model。設備是複雜對象的集合)

所以,你的模型應該是這樣的:

public List<Device> AvailableDevices { get;set; } 

public List<string> Devices { get;set; } 

和助手應該是

@Html.ListBoxFor(m=>m.Devices,new SelectList(Model.AvailableDevices , "ID", "Description")) 

@Html.DropDownListFor(m=>m.Devices,new SelectList(Model.AvailableDevices , "ID", "Description", new {multiple="multiple"}) 

後的行動應該得到無論是List<string>作爲參數或完整型號:

[HttpPost] 
public ActionResult Submit(List<string> devices) 

[HttpPost] 
public ActionResult Submit(YourModel model) 
//where YourModel model is the same type that you are using to render your view 
1

在這種情況下,我會做的視圖模型

內以下
public string Devices { get; set; } 
List<int> innerList; 
public List<int> List 
{ 
    get 
    { 
     if (this.innerList == null) 
     { 
      if (string.IsNullOrEmpty(this.Devices)) 
      { 
       this.innerList = this.Devices.Split(',').Select(x => int.Parse(x)).ToList(); 
      } 
      else 
      { 
       this.innerList = new List<int>(); 
      } 
     } 

     return this.innerList; 
    } 
} 

其中Devices是下拉菜單的綁定屬性,它將返回由,分隔的所有項目。 當您嘗試訪問List時,它將分離項目並將其作爲List<int>返回。

而且我也解析到int,因爲通常我看到int的作爲ID的

,但我期待着一個更好的選擇。

PS

我這樣做與Select2

相關問題