1

I have an HTML.dropdown multiple select2 working perfect. When I save values,

BUT: On update page I have to show the pre selected values in the dropdown

here is the code:

<div class="col-md-6 mb-3" id="categorylist">
   <p class="mb-1 font-weight-bold text-muted mt-3 mt-md-0">Category*</p>
   @Html.DropDownList("pCategory[]", new SelectList(new admin.Models.CategoryModel().getMultipleCategoryBySP(), "cat_id", "cat_name", --placeToProvideSingleIntValue--), 
     new { @class = " form-control select2-multiple ", @data_toggle = "select2", @multiple = "multiple", @style = "width: 100%;" })
</div>

in above code, there is a place holder --placeToProvideSingleIntValue-- where I can place single integer value it shows as preSelected.

Solution/HELP Required for: i want to pass an array to it or multiple values anyother way. so it would show multiple pre selected values.

A H
  • 85
  • 7
  • 1
    Have you tried the [MultiSelectList](https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.multiselectlist?view=aspnet-mvc-5.2) ? [This](https://stackoverflow.com/questions/3737985/asp-net-mvc-multiselectlist-with-selected-values-not-selecting-properly) could also help. – the_lotus Aug 20 '19 at 13:04
  • @the_lotus I can't thank you enough man. That solved my problem. Thanks a BILLION :) ;) – A H Aug 20 '19 at 13:12

2 Answers2

1

You'll have to use a MultiSelectList instead of a SelectList. Something like

@Html.DropDownList("pCategory[]", new MultiSelectList(new admin.Models.CategoryModel().getMultipleCategoryBySP(), "cat_id", "cat_name", --placeToProvideMultipleIntValue--), 
     new { @class = " form-control select2-multiple ", @data_toggle = "select2", @multiple = "multiple", @style = "width: 100%;" })
the_lotus
  • 12,668
  • 3
  • 36
  • 53
0

Razor-pages(near the Blazor thingy :D) is one of the newest and most modern frameworks from Microsoft for now, so I think you should try to use tag helpers wherever is possible as you can get so many benefits from using it! You can have a look at the sample here

So the tag component on your .cshtml page should look quite simple, like:

<select asp-for="pCategory" asp-items="items" multiple class="form-control select2-multiple" style="width: 100%;" data_toggle = "select2"></select>

where an item is a MultiSelectList object

MultiSelectList items = new MultiSelectList(Categories, "cat_id", "cat_name", 
selectedValues);

and selectedValues array of ints. Hope it will help :)

And just one small thing out of the scope. I don't think it is nice to do something like this

new admin.Models.CategoryModel().getMultipleCategoryBySP()

on your client-side. I believe that the right thing that should be done is to pass just a flat object to the client-side and keep the whole business logic/conversions/mapping stuff in the back-end.

Cheers

GoldenAge
  • 2,918
  • 5
  • 25
  • 63