1

I am using chosen multiselect drop down in my sample project

@Html.DropDownListFor(m => m.SelectedBranch, Model.BranchList, "Select", new { @class = "select-chosen form-control", @tabindex = "2", @id = "BranchId", @multiple = "multiple" })

and my model is

public string[] SelectedBranch { get; set; }
public IEnumerable<SelectListItem> BranchList { get; set; }

The issue I am facing is I am not able to display the selected values on editing the already added data. I am getting all the selected values from the db in Cntroller

. Please let me know what I have to do to achieve it. Any help will be appreciated. Thanks

Binoy Kumar
  • 422
  • 3
  • 17

1 Answers1

2

You need to use ListBoxFor() (and without new { multiple="multiple" }) to generate a multiple select that binds to your model

@Html.ListBoxFor(m => m.SelectedBranch, Model.BranchList, "Select", new { @class = "select-chosen form-control", @tabindex = "2", @id = "BranchId" })
  • If my SelectedBranch was a string instead of string array then can I do the same – Binoy Kumar May 23 '17 at 07:59
  • 1
    No. A `ListBoxFor()` generates a ` –  May 23 '17 at 08:09
  • As a side note,since this question, I added a more detailed explanation to a [similar question here](https://stackoverflow.com/questions/40725358/why-does-the-dropdownlistfor-lose-the-multiple-selection-after-submit-but-the-li/40732481#40732481) which explains why `DropDownListFor()` with `new { multiple = "multiple" }` does not work. –  May 23 '17 at 08:13
  • My issue is that I am having string as model and I am have all the pre selected values as a comma seperated string is it possible – Binoy Kumar May 23 '17 at 08:13
  • 1
    You editing data, therefore you should always be using a view model specific to the view, and that view model can contain a property `IEnumerable SelectedBranch` and then you can use `String.Join(...)` when you map the view model to the data model before saving, and `String.Split()` in the other direction. But why are you saving a comma separated string? That is considered terrible practice - refer [this answer](https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad) for just one of many Q/A on this site explaining why its bad. –  May 23 '17 at 08:28
  • Tanx @Stephen you are awsome – Binoy Kumar May 23 '17 at 08:40