0

I'm using the JQuery Select2 plugin from http://select2.github.io/select2/ and am having a problem binding a model to multiple items.

I know that when using Select2 for multiple items, you can create a separate entity to hold the stored items, but in my case I'd like to use a comma delimited list.

My view code is here:

<div class="col-xs-3">
    @Html.DropDownListFor(
    x => x.Quote.TypeofRoof,
    Model.RoofTypes,
    "", new { @class = "ddl", @multiple = "multiple", @style = "width:100%;height:35px" })
</div>

TypeofRoof is a string in my Quote class:

public string TypeofRoof { get; set; }

My problem is that when I submit my form with multiple items selected, only the first is saved:

enter image description here

enter image description here

What I'm after is to have the model comma separate the values, i.e.:

"Metal, Terracotta"

1 Answer 1

2

Use a ListBoxFor instead of DropDownListFor. Make you field array type:

public string[] TypeofRoof { get; set; }

And then on View:

@Html.ListBoxFor(
    x => x.Quote.TypeofRoof,
    Model.RoofTypes,
    new { @class = "ddl", multiple = "multiple", @style = "width:100%;height:35px" })
Sign up to request clarification or add additional context in comments.

4 Comments

The only problem with having TypeofRoof as a string[] is that I can't map it directly to an EntityFramework type?
actually it's poor practice map to your DB Layer (EF in your case) right from your View. Better use mapping ViewModel to EF Model in your Controller.
I'm getting an error with the ListBoxFor syntax, not sure what the problem is, but it's not syntaxed properly
Just FYI, Rooftypes is of type IEnumerable<SelectListItem>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.