Getting Multiple Selected Values in Html.DropDownlistFor
Asked Answered
B

3

40
@Html.DropDownListFor(m => m.branch, CommonMethod.getBranch("",Model.branch), "--Select--", new { @multiple = "multiple" })

@Html.DropDownListFor(m => m.division, CommonMethod.getDivision(Model.branch,Model.division), "--Select--", new { @multiple = "multiple" })

I have two instances of DropDownListFor. I want to set selected as true for those which have previously stored values for Model.branch and Model.division. These are string arrays of stored ids

class CommonMethod
{
    public static List<SelectListItem> getDivision(string [] branchid , string [] selected)
    {
        DBEntities db = new DBEntities();
        List<SelectListItem> division = new List<SelectListItem>();
        foreach (var b in branchid)
            {
                var bid = Convert.ToByte(b);
                var div = (from d in db.Divisions where d.BranchID == bid select d).ToList();
                foreach (var d in div)
                {
                    division.Add(new SelectListItem { Selected = selected.Contains(d.DivisionID.ToString()), Text = d.Description, Value = d.DivisionID.ToString() });
                }
            }
        }

        return division;
    }
}

The returned value of division is selected as true for the selected item in the model, but on view side it is not selected.

Bialy answered 29/8, 2012 at 11:19 Comment(2)
I don't get your question. Is it simply How to set a value selected in dropdownlist?Georgie
Yes, I want to get the values to be selected which are stored in database previously on page load.Bialy
T
71

Use a ListBoxFor instead of DropDownListFor:

@Html.ListBoxFor(m => m.branch, CommonMethod.getBranch("", Model.branch), "--Select--")

@Html.ListBoxFor(m => m.division, CommonMethod.getDivision(Model.branch, Model.division), "--Select--")

The branch and division properties must obviously be collections that will contain the selected values.

And a full example of the proper way to build a multiple select dropdown using a view model:

public class MyViewModel
{
    public int[] SelectedValues { get; set; }
    public IEnumerable<SelectListItem> Values { get; set; }
}

that would be populated in the controller:

public ActionResult Index()
{
    var model = new MyViewModel();

    // preselect items with values 2 and 4
    model.SelectedValues = new[] { 2, 4 };

    // the list of available values
    model.Values = new[]
    {
        new SelectListItem { Value = "1", Text = "item 1" },
        new SelectListItem { Value = "2", Text = "item 2" },
        new SelectListItem { Value = "3", Text = "item 3" },
        new SelectListItem { Value = "4", Text = "item 4" },
    };

    return View(model);
}

and in the view:

@model MyViewModel
...
@Html.ListBoxFor(x => x.SelectedValues, Model.Values)

It is the HTML helper that will automatically preselect the items whose values match those of the SelectedValues property.

Tiffaneytiffani answered 29/8, 2012 at 11:40 Comment(1)
What if I want to display all the values and then ask user to select multiple options and post multiple selected options after user submits? Is it possible with above approach.. If not could you please let me know how its done.. I could have created separate question but I feel that this answer is very near to what I want..Cortese
E
13

For me it works also for @Html.DropDownListFor:

Model:

public class MyViewModel
{
    public int[] SelectedValues { get; set; }
    public IEnumerable<SelectListItem> Values { get; set; }
}

Controller:

public ActionResult Index()
{
    var model = new MyViewModel();

    // the list of available values
    model.Values = new[]
    {
        new SelectListItem { Value = "2", Text = "2", Selected = true },
        new SelectListItem { Value = "3", Text = "3", Selected = true },
        new SelectListItem { Value = "6", Text = "6", Selected = true }
    };

    return View(model);
}

Razor:

@Html.DropDownListFor(m => m.SelectedValues, Model.Values, new { multiple = "true" })

Submitted SelectedValues in controller looks like:

enter image description here enter image description here

Emrick answered 2/12, 2015 at 14:45 Comment(2)
The difference is that you already set the listitem values to selected, in Model.Values, and you do not use SelectedValues at all. Try removing "selected = true" and add some int to SelectedValues, then it does not work as expected. Not for me anyway.Convolute
Did not work for me as expected by the answer. Clearly it's true what @MartinBring has pointed out. May be the answer needs little bit of editing. I don't know how it got so many up votes, wonder if they actually tried it before voting.Katzen
K
1

Though quite old thread but posting this answer after following other answers here, which unfortunately didn't work for me. So, for those who might have stumbled here recently or in near future, Below is what has worked for me.

This is what helped me

The catch for me was MultiSelectList class and I was using SelectList.

Don't know situation in 2012 or 2015. but, now both these helper methods @Html.DropDownListFor and @Html.ListBoxFor helper methods accept IEnumerable<SelectListItem> so you can not pass any random IEnumerable object and expect these helper methods to do the job.

These helper methods now also accept the object of SelectList and MultiSelectList classes in which you can pass the selected values directly while creating there objects.

For example see below code how i created my multi select drop down list.

@Html.DropDownListFor(model => @Model.arrSelectUsers, new MultiSelectList(Model.ListofUsersDTO, "Value", "Text", @Model.arrSelectUsers),
                                                    new
                                                    {
                                                        id = "_ddlUserList",
                                                        @class = "form-control multiselect-dropdown",
                                                        multiple = "true",
                                                        data_placeholder = "Select Users"
                                                    })
Katzen answered 24/1, 2020 at 16:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.