Multiple selection of ListBox is not working in asp.net mvc4

独自空忆成欢 提交于 2020-01-15 19:11:14

问题


I have bound listbox data from entity framework. I have selected multiple values in that listbox. But, the values are not fired. The count of the property is 0 only. I am using the code below:

public class Sample1  
{  
[Key]  
public int SampleId{ get; set; }  
public string SampleDesc{ get; set; }  
}
public class ExpModel  
{  
public List<Sample1> Sample{ get; set; }  
}
public ActionResult Index()  
{       
ViewData["SampleList"] = new List<Sample1>(entity.samp);  
return View();  
} 
@Html.ListBoxFor(model => model.Sample, new  SelectList(((List<Details.Models.Sample1>)ViewData["SampleList"]), "SampleId", "SampleDesc")) 

What do I have to do? Please help me...


回答1:


You should bind the ListBoxFor helper to a property that is a collection of simple/scalar values such as strings or integers:

public class Sample1  
{  
    [Key]  
    public int SampleId { get; set; }  
    public string SampleDesc { get; set; }  
}

public class ExpModel  
{  
    public List<int> SelectedSampleIds { get; set; }  
}

and then:

public ActionResult Index()  
{       
    ViewData["SampleList"] = new List<Sample1>(entity.samp);
    return View();  
}

and in your view:

@Html.ListBoxFor(
    model => model.SelectedSampleIds, 
    new SelectList(
        (List<Details.Models.Sample1>)ViewData["SampleList"], 
        "SampleId", 
        "SampleDesc"
    )
)

Now when you submit the form, the SelectedSampleIds collection will contain the selected ids in the list box.



来源:https://stackoverflow.com/questions/18104110/multiple-selection-of-listbox-is-not-working-in-asp-net-mvc4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!