How to create multiple select @html.dropdownlistfor in mvc
Loading
How to create multiple select @html.dropdownlistfor in mvc
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sachin SinghPosted Dec 7, 2021, 3:48 PM
Yazhini MPPosted Dec 8, 2021, 7:28 AM
An example to build a multiple select dropdown using a view model: Values { get; set; }
public class MyViewModel
{
public int[] SelectedValues { get; set; }
public IEnumerable
}
that would be populatd in the controller
public ActionResult Index()
{
var model = new MyViewModel();
// preselect items with values 2 and 4
model.SelectedValues = new[] {2,4};
// the list of available values
model.Values = new[]
{
new SelectListItem {value = "1", Text = "item 1"},
new SelectListItem {Value = "2", Text = "item 2"},
new SelectListItem {Value = "3", Text="item 3"};
new SelectListItem {Value = "4",Text="item 4"};
};
return View(model);
}
and in the view:
@model MyViewModel
@Html.ListBoxFor(x=> x.SelectedValues, Model.Values)
AishwaryaPosted Dec 8, 2021, 7:18 AM
Please use ListBox for mulitple select in dropdown box.@Html.ListBoxFor(m => m.location_code, Model.location_type)Srinivasan RamamoorthiPosted Dec 7, 2021, 12:58 PM
Lakshna SPosted Dec 7, 2021, 11:15 AM
Use a ListBoxFor instead of DropDownListFor:
@Html.ListBoxFor(m => m.name, Method.getName("", Model.name), "--Select--")
@Html.ListBoxFor(m => m.department,Method.getDepartment(Model.name, Model.department), "--Select--")
The name and department properties must obviously be collections that will contain the selected values.
The HTML helper will automatically preselect the items whose values match those of the Name/Department property.