1

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...

user2687153
  • 427
  • 5
  • 24
  • There are some answers here https://stackoverflow.com/questions/21878673/html-enumdropdownlistfor-showing-a-default-text. Maybe can help you. – pnet May 07 '19 at 13:28
  • This links explains how to select ONE element in an EnumDropDownListFor. This works but doesn't answer my problem, which is : how to select MULTIPLE elements in the drop down, and bind it with my model property – user2687153 May 07 '19 at 13:31
  • If you change this code snippet `@multiple = "multiple"` to `multiple = "true"` – pnet May 07 '19 at 13:58
  • I already tried it (see my examples in my original post) and unfortunately doesn't work – user2687153 May 07 '19 at 14:32

1 Answers1

0

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

Matt M
  • 1,093
  • 2
  • 11
  • 26
  • Hi, thanks for your answer. I worked with KO in a previous project and it should work, however this is a personal project and I don't want to add a JS framework juste for one binding in one screen. – user2687153 May 07 '19 at 13:25
  • I get that, but what you have is sever-side binding. Once it leaves the server, you're not going to be able to do anything without some JS. So either you're going to need JS to do this for you client-side, or you're going to need to use a framework such a KO. There is nothing OOTB in C# to auto-generate client-side JS to do this work for you. – Matt M May 07 '19 at 13:54