简体   繁体   中英

Bind multiple values on EnumDropDownListFor / ListBoxFor

I'm using ASP.NET MVC5 and I'm trying to create an EnumDropDownListFor where :

  • User may select multiple values (in a drop down filled with enum values)
  • The selected values are binded to the model when the form is submitted.

Here is what I tried so far :

@Html.ListBoxFor(m => m.SelectedHeatingTypes, new SelectList(Model.HeatingTypeItems, "Value", "Text"))
@Html.ListBoxFor(m => m.SelectedHeatingTypes, Model.HeatingTypeItems, new { @class = "form-control" })
@Html.ListBoxFor(m => m.SelectedHeatingTypes, new MultiSelectList(Model.HeatingTypeItems, "Value", "Text"))
@Html.EnumDropDownListFor(m => m.HeatingTypes, new { @class = "form-control selectpicker", @multiple = "multiple"})
@Html.ListBoxFor(m => m.HeatingTypes, Model.HeatingTypeItems, htmlAttributes: new { @class = "form-control", multiple = "multiple" })
@Html.ListBoxFor(m => m.HeatingTypes, new SelectList(Enum.GetValues(typeof(HeatingType))), new { @id = "ddlMyEnum", @multiple = "multiple" })

On my model, I have thiese two properties

public IEnumerable<int> SelectedHeatingTypes { get; set; }
public IEnumerable<SelectListItem> HeatingTypeItems { get; set; }

I tried to change the IEnumerable<int> SelectedHeatingTypes to int[] , no more success

How can I bind the multi selection on a model property ? I'm open to Arrays, Lists, IEnumerable<>, everything I can work with server side...

I would check out KnockoutJs as that may solve your issue. That is a client-side binding, though, so you'd need to get your model to the client and then use KO to bind the data to your UI.

https://knockoutjs.com/documentation/selectedOptions-binding.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM