Asp.net mvc 4 如何使用DropDownList for以便选择多个值?

Asp.net mvc 4 如何使用DropDownList for以便选择多个值?,asp.net-mvc-4,Asp.net Mvc 4,我有一个模型,在这个模型中我创建了一个列表来选择多个值,这些值在HTML上显示。这些值来自IList。因此,现在,我需要在我的模型中添加多个值,但我不能这样做,我正在选择多个值,但当我提交时,列表为空 我怎么能这样做 努力 型号 public class EmpresaModel{ [Required(ErrorMessage="Informe ao menos uma forma de pagamento disponível")] public List<SelectL

我有一个模型,在这个模型中我创建了一个
列表
来选择多个值,这些值在HTML上显示。这些值来自
IList
。因此,现在,我需要在我的模型中添加多个值,但我不能这样做,我正在选择多个值,但当我提交时,
列表
为空

我怎么能这样做

努力

型号

public class EmpresaModel{
    [Required(ErrorMessage="Informe ao menos uma forma de pagamento disponível")]
    public List<SelectListItem> formasPagto { get; set; }
}
公共类模型{
[必需(ErrorMessage=“通知pagamento disponível的形式”)]
公共列表格式为{get;set;}
}
控制器

private List<SelectListItem> getFormasPagto() {
    IList<FormaPagamento> lista = fpDAO.findAll();
    List<SelectListItem> dropDown = new List<SelectListItem>();
    foreach (FormaPagamento x in lista) {
        dropDown.Add(new SelectListItem { Text = x.descricao, Value = Convert.ToString(x.id)});
    }
    return dropDown;
}

public ActionResult add() {
    EmpresaModel model = new EmpresaModel();
    model.formasPagto = getFormasPagto();
    return View(model);
}

public JsonResult addAjax(EmpresaModel model) {     
   Debug.WriteLine("Formas Pagto: " + model.formasPagto.Count);
   return Json(jsonResposta);
}
私有列表getFormasPagto(){
IList lista=fpDAO.findAll();
列表下拉列表=新建列表();
foreach(列表中的FormaPagamento x){
添加(新的SelectListItem{Text=x.descripa,Value=Convert.ToString(x.id)});
}
返回下拉列表;
}
公共行动结果添加(){
EmpresaModel=新EmpresaModel();
model.formasPagto=getFormasPagto();
返回视图(模型);
}
公共JsonResult addAjax(EmpresaModel模型){
Debug.WriteLine(“Formas Pagto:+model.formasPagto.Count”);
返回Json(jsonResposta);
}
HTML

@model EmpresaModel
<div class="form-group">
    <label for="name" class="cols-sm-2 control-label">Formas de pagamento disponíveis <img src="~/Imagens/required.png" height="6" width="6"></label>
    @Html.DropDownListFor(model => Model.formasPagto, Model.formasPagto, new { Class = "form-control", placeholder = "Selecione as formas de pagamento disponíveis", @multiple = true})
    @Html.ValidationMessageFor(model => Model.formasPagto)
</div>
@model-EmpresaModel
帕加门托会议形式
@Html.DropDownListFor(model=>model.formasPagto,model.formasPagto,new{Class=“form control”,placeholder=“Selecione as formas de pagamento disponíveis”,@multiple=true})
@Html.ValidationMessageFor(model=>model.formasPagto)

formasPagto
IEnumerable
-不能将
绑定到复杂对象的集合。
只回发一个简单值数组(所选选项的值)

例如,您的模型需要绑定到一个属性

[Required(ErrorMessage="Informe ao menos uma forma de pagamento disponível")]
public IEnumerable<int> SelectedItems { get; set; }
旁注:您可以简单地使用

model.formasPagto = new SelectList(fpDAO.findAll(), "id", "descricao");

要生成
选择列表

model.formasPagto = new SelectList(fpDAO.findAll(), "id", "descricao");
model.formasPagto = fpDAO.findAll().Select(x => new SelectListItem
{
    Value = x.id.ToString(),
    Text = descricao
});