问题
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