Tuesday 18 February 2014

MVC 4 - Populate a DropDownList

I'll keep this simple as most other examples seem not to be :D

For example in your controller:

 public ActionResult MyDropDownList()
        {
            ViewBag.MyType = GetDropDownList();

            return View("");
        }

        public static List GetDropDownList()
        {
            var ls = new List
            {
                new SelectListItem() {Text = "Bob", Value = "0"},
                new SelectListItem() {Text = "Jeff", Value = "1"},
                new SelectListItem() {Text = "Rob", Value = "2"}
            };

            return ls.OrderBy(x => x.Text).ToList();
        }

In your razor script/cshtml:

@Html.DropDownList("MyType", MyController.GetDropDownList())

Hopefully that will help you to get your populated dropdown list :)


Additional

You can put this in your razor script for example:

var amountList = new List();
    for (var i = 0; i <= 10; i++)
    {
        amountList.Add(new SelectListItem { Text = i.ToString(CultureInfo.InvariantCulture), Value = i.ToString(CultureInfo.InvariantCulture) });
    }
    amountList = amountList.ToList();
}


Then for display purposes:



                        @Html.DropDownListFor(model => model.ReceptionRooms,  amountList)
                        @Html.ValidationMessageFor(model => model.ReceptionRooms) 



This will display a dropdown from 1-10, the beauty of this also is that you can reuse the same list for multiple controls.

No comments: