如何多选ListBox asp.net

时间:2015-04-21 12:20:25

标签: c# asp.net asp.net-mvc listbox

我创建了一个包含asp.net razor的列表框。但我希望能够多选列表框。我该怎么做?

我想使用这样的东西:

[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
    }
}
  

编译器错误消息:CS0411:方法的类型参数   &#39; System.Web.Mvc.Html.SelectExtensions.ListBoxFor(System.Web.Mvc.HtmlHelper,   System.Linq.Expressions.Expression&gt;中   System.Collections.Generic.IEnumerable)&#39;   无法从使用中推断出来。尝试指定类型参数   明确。

     

来源错误:   @ Html.ListBoxFor(&#34; VarFromKenmerkTEST&#34;(MultiSelectList)ViewBag.var),   新{@style =&#34;宽度:252px;身高:300px;&#34;})

并且我不知道KenmerkSelectie中的参数是否良好。

2 个答案:

答案 0 :(得分:1)

您应该使用viewModel将数据传递到视图(强类型),然后使用

创建列表框
@Html.ListBoxFor(viewmodel => viewmodel.model.property, viewmodel.data )

viewmodel的data属性应为Multiselectlist

视图模型:

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

    public Model model { get; set; }
}

答案 1 :(得分:0)

您需要设置SelectList类的Selected属性以及添加属性new {Multiple =“multiple”}

@{
    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"})