Reputation: 15958
I have this function that returns the type IEnumerable<SelectListItem>
.
public IEnumerable<SelectListItem> GetItems()
{
IEnumerable<SelectListItem> results = null;
results =*(some logic)*
return results;
}
I try to bind this to dropdown in a view using
<% foreach (IEnumerable<SelectListItem> schdItem in Model.GetItems())
{%>
<%= Html.DropDownList("xxx", schdItem)%>
<%} %>
But it breaks with the error message
Unable to cast object of type 'System.Web.Mvc.SelectListItem' to type 'System.Collections.Generic.IEnumerable`1[System.Web.Mvc.SelectListItem]'.
How do I fix this?
Based on the comment from asawyer I modified it to
<%= Html.DropDownList("xxx", Model.GetScheduleItems())%>
now it works!
Upvotes: 0
Views: 327
Reputation: 93464
<%= Html.DropDownList("xxx", Model.GetItems())%>
Althought this is a terrible way to go about it. Instead, you should be using Html.DropDownListFor such as this:
<%= Html.DropDownListFor(Model.SelectedItem, Model.Items) %>
Where Model.SelectedItem is the type of item, and Model.Items is a property that returns a collection of SelectListItems.
Upvotes: 1
Reputation: 50523
No loop needed, just this.
<%= Html.DropDownList("xxx", Model.GetItems())%>
I would make the SelectList
a property on your model rather than a getter method.
<%= Html.DropDownList("xxx", Model.MySelectList)%>
Upvotes: 1