Friday, October 8, 2010

MVC2 Dropdown lists

view
<%= Html.DropDownList("Text", (IEnumerable)ViewData["IntervalTime"]) %>
the first piece has to be the name of the Text field in your list if you want your selected = true value to truly show as selected.

Second piece is your SelectList
optional third piece is a SelectListItem you want to manually add to the DropDownList


Controller
ViewData["IntervalTime"] = new Domain.IntervalList().IntervalDropDownList.Items;

i used ViewData because i am returning other Data as a Partial View.


Class of Data Items for the DropDownList
    public class IntervalList
    {
        private List _items = new List();
        private SelectList _intervalDropDownList = null;

        public SelectList IntervalDropDownList
        {
            get
            {
                return _intervalDropDownList;
            }
        }


        public IntervalList()
        {
            _items.Add(new SelectListItem { Text = "30", Value = "30" });
            _items.Add(new SelectListItem { Text = "60", Value = "60" });
            _items.Add(new SelectListItem { Text = "90", Value = "90" });
            _items.Add(new SelectListItem { Text = "All", Value = "All", Selected = true });

            _intervalDropDownList = new SelectList(_items);
        }
    }

No comments: