System.InvalidCastException iterating through Viewdata
I need to replace the code
"<%=Html.DropDownList("Part", (SelectList)ViewData["Parts"])%>
for dropdown in the following manner for some reason.
<select> <% foreach (Hexsolve.Data.BusinessObjects.HSPartList item in (IEnumerable<Hexsolve.Data.BusinessObjects.HSPartList>)ViewData["Parts"])
{ %>
<option value="<%=item.Id %>">
<%=item.PartName %>
<%=item.IssueNo %></option>
<% } %>
</select>
I am getting error converting SelectedList to IEnumerable)
Error: Unable to cast object of type ‘System.Web.Mvc.SelectList’ to type ‘System.Collections.Generic.IEnumerable`1[Hexsolve.Data.BusinessObjects.HSPartList]’.
Is this the right way to iterate through viewdata[]. Please help me out of this.
Sorry my previous answer was incorrect.
I believe the problem is that
GetEnumeratorreturnsIEnumerator<SelectListItem>, notIEnumerator<Hexsolve.Data.BusinessObjects.HSPartList>which you are trying to access.I would suggest something like the following should work:
If you need to concatenate
PartNameandIssueNoin theTextproperty which it looks like you’re trying to do, you could do that while building the select list.So you might end up with something like:
and
Hope that helps!