2015-04-21 57 views
-1

我創建了一個列表框asp.net razor。但我想能夠多選列表框。我怎麼做?如何多選列表框asp.net

我想用這樣的:

[HttpPost] 
public ActionResult KenmerkSelectie(List<string> VarFromKenmerk1) 
{ 

} 

下面的列表框的職位只有一個變量:

@using (Html.BeginForm("KenmerkSelectie", "KenmerkSelectie", FormMethod.Post, new { id = "kenmerk1" })) 
{ 
    @Html.ListBox("VarFromKenmerk1", (SelectList)ViewBag.var) 
    <input type="submit" value="submit"/> 
} 

編輯: 我想下面的代碼,但我得到一個錯誤:

@using (Html.BeginForm("KenmerkSelectie", "KenmerkSelectie", FormMethod.Post, new { id = "kenmerk1" })) 
{ 
    @Html.ListBoxFor("VarFromKenmerkTEST",(MultiSelectList)ViewBag.var), new {@style = "width: 252px; height: 300px;"}) 
    <input type="submit" value="submit"/> 
} 


public ActionResult index() 
{ 
    ViewBag.VarFromKenmerk1 = new List<SelectListItem>(); 
    ViewBag.VarFromKenmerk1.Add(new SelectListItem 
    { 
     Value = "House", 
     Text = "House" 
    }); 

    ViewBag.VarFromKenmerkTEST = new MultiSelectList(ViewBag.VarFromKenmerk1); 
    return View(); 
} 


[HttpPost] 
public ActionResult KenmerkSelectie(List<string> VarFromKenmerkTEST){ 
    foreach(var ken in VarFromKenmerkTEST){ 
     //selected items 
    } 
} 

Compiler Error Message: CS0411: The type arguments for method 'System.Web.Mvc.Html.SelectExtensions.ListBoxFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>, System.Collections.Generic.IEnumerable)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Source Error: @Html.ListBoxFor("VarFromKenmerkTEST",(MultiSelectList)ViewBag.var), new {@style = "width: 252px; height: 300px;"})

我不知道KenmerkSelectie中的參數是否好。

+0

你是什麼意思_「只發布1個變量」_?它會回發一組綁定到你的參數的值(如果你選擇了3個選項,那麼'VarFromKenmerk1'將包含3個值) –

+0

[編輯視圖中的超級簡單實現多選列表框的可能的重複] (http://stackoverflow.com/questions/18363158/super-simple-implementation-of-multiselect-list-box-in-edit-view) –

回答

1

您應該使用視圖模型將數據傳遞到您的視圖(強類型)和然後創建

@Html.ListBoxFor(viewmodel => viewmodel.model.property, viewmodel.data) 

您的列表框的視圖模型的數據屬性應該是一個Multiselectlist

視圖模型:

public class viewModel 
{ 
    public MultiSelectList data { get; set; } 

    public Model model { get; set; } 
} 
+0

我不想使用模型...是不是可以使用ListBox – user3432681

+0

你可以在viewbag中放置一個multiSelectList – Gelootn

+0

我編輯了我的問題can你看看它? – user3432681

0

你需要設置的SelectList類的Selected屬性以及添加屬性新{多個=「多」}

@{ 
    var VarFromKenmerk1= new List<SelectList> { 
     new SelectList{ Text = "Text1", Value = "Value1", Selected = true }, 
     new SelectList { Text = "Text2", Value = "Value2" }, 
     new SelectList { Text = "Text3", Value = "Value3", Selected = true } 
    }; 
} 

@Html.ListBox("VarFromKenmerk1", VarFromKenmerk1, new {Multiple = "multiple"}) 
+1

'@ Html.ListBox()'和'@ Html.ListBoxFor( )'助手添加了'multiple =「multiple」''屬性 –