1

I have a control that needs to have multiple select options to create tokens. Whenever the token is created or deleted DB call is generated. Now the problem is when I load a fresh page from the server there is no token in the control. Following is my Razor code:

@Html.DropDownList("ProjectIds", new MultiSelectList(projDDL.Items, "key", "value",Model.SelectedProject), new {@class = "form-control selectorBind", multiple = "multiple",@id= "myid" data_rowid = "ID", data_type="Project",data_myattr= "attr" })

projDDL is a dictionary that contains the dropdown list items

SelectedProject are also dictionary containing selected projects key, value

I have tried to follow this link MVC DropDown list with MultipleSelect but no luck.

Loading tokens from server side is my problem. Though I know I can do it easily from Jquery but I want to use Razor for it.

Solution Check out @Html.DropDownListFor vs @Html.ListBoxFor

@Html.ListBoxFor(y => y.SelectedProjects, new MultiSelectList(projDDL.Items, "key", "value", Model.SelectedProjects), new { @class = "form-control selectorBind", multiple = "multiple", @id = @Model.SkillType+"Project_" + Model.ID, data_rowid = @Model.ID, data_type = "Project", data_myattr = "FK_ProjectID" })
JB's
  • 606
  • 13
  • 30
  • 1
    Use `ListBoxFor()` not `DropDownListFor()` for generating a multiple select. And `SelectedProjects` needs to be a collection of simple values (matching the values of your options) not a `Dictionary` –  Jul 27 '17 at 08:49
  • 1
    Refer also [this answer](https://stackoverflow.com/questions/40725358/why-does-the-dropdownlistfor-lose-the-multiple-selection-after-submit-but-the-li/40732481#40732481). And does your model contain a property named `ProjectIds` i if so then then your `Model.SelectedProject` argument is ignoired - its the value of `ProjectIds` that determines which options are selected –  Jul 27 '17 at 08:53
  • I want to something like [this](https://select2.github.io/examples.html). `ListBoxFor()` is not what I am looking for. If you want me to use a collection for `SelectedProjects` than for predefined projects that construct the Dropdown should they also be a collection? – JB's Jul 27 '17 at 08:54
  • 1
    Yes it is! Read the link to explain why. And it makes no difference to the appearance - (they generate identical html) - your applying a jquery plugin –  Jul 27 '17 at 08:56
  • The answer was full of information and cleared the air. Thanks for your time and attention. – JB's Jul 27 '17 at 09:07

1 Answers1

6

Check out difference between @Html.DropDownListFor and @Html.ListBoxFor and when to use what

@Html.ListBoxFor(y => y.SelectedProjects, new MultiSelectList(projDDL.Items, "key", "value", Model.SelectedProjects), new { @class = "form-control selectorBind", multiple = "multiple", @id = @Model.SkillType+"Project_" + Model.ID, data_rowid = @Model.ID, data_type = "Project", data_myattr = "FK_ProjectID" })
JB's
  • 606
  • 13
  • 30