Florin M. Florin M. - 3 months ago 8
ASP.NET (C#) Question

Fill values for mvc dropdownlist

@Html.DropDownListFor(x => x.Pets, new SelectList(ViewBag.Pets, "key", "value"), new { @class = "type1 newdrop" })


I'm newbie in mvc development. Using the above line of code, I'm getting the dropdown list but only with
2
as value.

How can I fill the dropdownlist to all values lower than
2
, including
0
? I want the selected item to be
2


ViewBag.Pets = Constants.MaxP.Where( x => x.Key == someId); // the someId is for sure one of the below key numbers


where

public static Dictionary<int, int> MaxP = new Dictionary<int, int>(){
{12, 2}, {13, 2}, {14, 2}, {15, 2}, {16, 2}, {17, 2}, {18, 2}
};

Answer

Turn your dictionary into a collection of SelectListItem like this:

int a = Constants.Maxp.FirstOrDefualt(x => x.Key == SomeID).Value;

List<SelectListItem> lst = new List<SelectListItem>();

for (int i = 0; i < a; i++)
{
    lst.Add(new SelectListItem(){
        Text = i.ToString(),
        Value = i.ToString()
    });
}

ViewBag.Pets = lst;

And then in your View:

@Html.DropDownListFor(x => x.Pets, ViewBag.Pets, new { @class = "type1 newdrop" })

Where x.pets is the ID that matches the Key