Click here to Skip to main content
15,074,483 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
I need a way to set already selected values in a multi select dropdown in a edit view in a web application (ASP.NET, Mvc)

from view code,I passed selected ids in to selected values array.(when I return values from DB , assign those in to a array then assign to here.

I need a edit view by set selecting already selected values.

please anyone suggest way to do this

Thank you.

What I have tried:

HTML
//View
    <div class="form-group">
    <label>Choose Categories</label>
    @Html.DropDownListFor(model => model.SelectedValues, new MultiSelectList(Models.GetCategoryList().OrderBy(c => c.Value), "Key", "Value"), "Select Category", new { @class = "chzn-select form-control", multiple = "multiple" })                               
    </div>


C#
//Model    
public int[] SelectedValues { get; set; }


C#
//Controller
        public ActionResult Edit(int id)
        {         
            return View(GetDetails(id));
        }


In GetDetails(id) take values from DB , and return a model object

C#
public GetDetails()
{
            int[] arr = new int[2];
            arr[0] = 4;
            arr[1] = 5;
            modelObj.SelectedValues = arr;
.......
......
return modelObj;
}
Posted
Updated 6-Aug-20 3:28am

You need to pass the selected values to the MultiSelectList[^] constructor.

It would also be more correct to use the ListBoxFor method, since you're not rendering a drop-down list.
@Html.ListBoxFor(model => model.SelectedValues, new MultiSelectList(Models.GetCategoryList().OrderBy(c => c.Value), "Key", "Value", Model.SelectedValues), "Select Category", new { @class = "chzn-select form-control", multiple = "multiple" })

ASP.NET MVC DropDownLists - Multiple Selection and Enum Support[^]
   
Um problema de 2017 resolvendo meu problema em 2020. Parabens Valeu!!
   
Comments
Richard Deeming 6-Aug-20 9:46am
   
"Me too" is not a solution to this already-solved question.
CHill60 6-Aug-20 10:53am
   
Existe um hiperlink "Have a Question or Comment?" (Tem uma pergunta ou comentário?) que você pode usar para fazer comentários como esses. Obrigado.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900