I want to create a dropdownlist with the ability to set the ID as well (as I have two going from the same viewbag). something like
@Html.DropDownList("startTimes", (SelectList)ViewBag.times, new { @class = "date" })
@Html.DropDownList("endTimes", (SelectList)ViewBag.times, new { @class = "date" })
Right now, I have
ViewBag.times = getTimeList();
private List<SelectListItem> getTimeList() { List<SelectListItem> times = new List<SelectListItem>(); for (int Minutes = 60; Minutes < 770; Minutes += 30) { TimeSpan TS = TimeSpan.FromMinutes(Minutes); String TSString = String.Format("{0:00}:{1:00}", TS.Hours, TS.Minutes); SelectListItem item = new SelectListItem(); item.Text = TSString; item.Value = TS.Minutes.ToString(); times.Add(item); } return times; }
But I am getting an error: Cannot convert type ‘System.Collections.Generic.List’ to ‘System.Web.Mvc.SelectList’
Here you go
As stated by the error you need to create a new
SelectListfor this to work and not just cast from your existing enumerable. TheDropDownListhelper overloads should show you that.You could also have googled the question and found the answer yourself, like in this SO question for example.
UPDATE:
Just reread your question now and you are talking about setting the
idfor the dropdownlist, that is not actually related to your error. Theidwill be set from the first parameter to theDropDownListhelper (it is the “name” parameter in the method).