System.InvalidCastException iterating through Viewdata
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 GetEnumerator
returns IEnumerator<SelectListItem>
, not IEnumerator<Hexsolve.Data.BusinessObjects.HSPartList>
which you are trying to access.
I would suggest something like the following should work:
<% foreach (SelectListItem item in (SelectList)ViewData["Parts"])
{ %>
<option value="<%= item.Value %>"><%= item.Text %></option>
<% } %>
If you need to concatenate PartName
and IssueNo
in the Text
property 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:
public class Part
{
public int Id { get; set; }
public int IssueNo { get; set; }
public string PartName { get; set; }
}
and
var parts = new List<Part>{
new Part { Id = 1, IssueNo = 1, PartName = "Spanner" },
new Part { Id = 2, IssueNo = 1, PartName = "Hammer" }
};
var selectList = new SelectList(
parts.Select(p =>
new { Id = p.Id,
Name = p.PartName + " " + p.IssueNo.ToString()}),
"Id",
"Name");
foreach (var item in selectList)
{
Console.WriteLine(item.Value);
Console.WriteLine(item.Text);
}
/*
Output:
1
Hammer 1
2
Spanner 1
*/
Hope that helps!
精彩评论