I'm trying to do a multiple selection with ListBoxFor of Razor, but the select does not allow me to select multiple items (I can do that only selecting my items with Ctr+click the second item). I've reduced my code to minimal like the exemple shown in this answer (my code is above). Anyone can help me?? I'm desperate.
My Model
public IEnumerable<int> ParoleChiave { get; set; }
public IEnumerable<SelectListItem> ListaParoleChiave { get; set; }
My Controller
model.ListaParoleChiave = new List<SelectListItem>() {
new SelectListItem(){ Text = "Pro", Value = "2"},
new SelectListItem(){ Text = "Test", Value = "3"}
};
My View
<div class="form-group form-group-sm">
<label class="col-xs-12">Parole chiave</label>
<div class="col-xs-12">
@Html.ListBoxFor(m => m.ParoleChiave, Model.ListaParoleChiave, new { @class = "form-control", style = "width: 100%" })
</div>
</div>
I found the error. It's not depending from my ListBoxFor element, it was caused by the js code that I wrote to post to the server action my formData with additional data. Basically it was like:
data: function (d) {
var fd = new FormData(myForm[0]);
for (var pair of fd.entries()) {
d[pair[0]] = pair[1];
}
return d;
}
I realized that the multiple values where posting like two entries (key/value pairs) of the FormData but with the same key name, so my code was overwriting the first entry with the second. I replaced with the code above and now it works like a charm.
data: function (d) {
var fd = new FormData(myForm[0]);
for (var pair of fd.entries()) {
var occurenceOfKey = Array.from(fd.keys()).reduce(function (n, val) {
return n + (val === pair[0]);
}, 0);
if (occurenceOfKey > 1)
d[pair[0]] = fd.getAll(pair[0]);
else
d[pair[0]] = pair[1];
}
return d;
}