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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sachin SinghRank #66 · 26.2K reputationPosted Dec 7, 2021, 10:48 AM EST
@Html.ListBoxFor() insted of @Html.dropdownlistfor()if you use @Html.dropdownlistfor() then use HtmlAttributes and define the multiple property.@Html.DropDownListFor(m => m.anyProp, Model.AnyList, new { @multiple = "multiple" }).Srinivasan RamamoorthiRank #877 · 2.5K reputationPosted Dec 7, 2021, 7:58 AM EST
Lakshna S39 reputationPosted Dec 7, 2021, 6:15 AM EST
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.
Aishwarya24 reputationPosted Dec 8, 2021, 2:18 AM EST
@Html.ListBoxFor(m => m.location_code, Model.location_type)Yazhini MP128 reputationPosted Dec 8, 2021, 2:28 AM EST
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)