Fill Dropdownlist with Multiple Values

Asked

Viewed 56 times

0

i am trying to fill a Dropdownlist that has multiple values, from my "Edit" action, where I recover the objects Toonmoves containing One or More Effects and how The Effects May belong to several Toonmoves, a relationship arose N:N, according to the image below:

DB Model

In my EDIT Action, I return to the view the object Toonmoves and in Viewbag the values of Effect

        ToonMoves toonMoves = movesService.Get(id.Value);
        ViewBag.Effects = new MultiSelectList(effectsService.GetAll(), "EffectID", "Name", toonMoves.MoveEffects);
        ViewBag.ToonID = new SelectList(toonService.GetAll(), "ToonID", "Name");
        ViewBag.TargetID = new SelectList(targetService.GetAll(), "TargetID", "TargetType", toonMoves.TargetID);
        return View(toonMoves);

Note that already return to Viewbag as Multiselectlist, and in View, is like this:

@Html.DropDownList("idsEffects", (MultiSelectList)ViewBag.Effects, htmlAttributes: new { multiple = "multiple", @class = "selectpicker", data_style = "select-with-transition", title = "Choose Move Effects", data_size = "7" })

But in View, the field does not come with any selected value:

inserir a descrição da imagem aqui

I need to make the object values Effects that are in the Object Toonmoves appear selected

Itens Selecionados

My Dropdownlist has the name "idsEffects", because I get a list of the values in int, I search the objects in the table Effects and add in Moveeffects.

I need a solution to keep these values marked when loading the Edit View, I’m willing to try solutions in Jquery, Js, Angularjs... Can anyone help me? If I need to, I will provide more details. Thank you!

  • What you have in toonMoves.Moveeffects property?

  • Contains Effects and Toonmoves Ids, as shown in the screenshot: link

  • And where are you declaring that these should come selected? you need to take to the view the list of items that the object has and when mounting the dropdown mark those that are contined in that list

  • I always use with an array by passing the id’s of the selected ones. Try to do the same, or try to pass the property (I don’t know if it works, never tested). For example: toonMoves.MoveEffects.ID

1 answer

1


You’d have to go through your MultiSelectList the values that will be selected:

ViewBag.Effects = new MultiSelectList(effectsService.GetAll(), "EffectID", "Name", new[]{1,2,3} );

In case it would return the selected items 1,2 and 3.

Reference: iMasters

That would be the implementation of the method:

public MultiSelectList(
  IEnumerable items,
  string dataValueField,
  string dataTextField,
  IEnumerable selectedValues
)
  • 1

    Thanks, buddy, I had to go through a loop to get the Ids and then I sent it to Multiselectlist and it worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.