ASP.NET MVC:奇怪的typecasing错误

时间:2009-10-23 13:35:47

标签: asp.net-mvc linq-to-entities

奇怪的类型转换错误:System.string - > weekmenu.SimpleTable

控制器

Function Index() As ActionResult

    ViewData("ListFrontName") = WeekMenuRepository.ListFrontName()
    ViewData("ListLastName") = WeekMenuRepository.ListLastName()
    Return View()

End Function

WeekMenuRepository

Public Function ListFrontName() Implements IWeekMenuRepository.ListFrontName

    Dim jow = From p In SimpleTable.SimpleTable Select p
    Return jow

End Function

查看

<%  For Each item As SimpleTable In ViewData("ListFrontName")%>

<p><%=item.SimpleName%></p>

<%Next%>

当我运行这个时,我会按预期工作(我得到一个正名列表)

但是如果我在WeekMenuRepository中更改了这个,我会得到一个类型转换错误,为什么会这样,我做错了什么以及如何解决?

WeekMenuRepository(已更改)

=&GT;补充:选择p.SimpleName

Public Function ListFrontName() Implements IWeekMenuRepository.ListFrontName

    Dim jow = From p In SimpleTable.SimpleTable Select p.SimpleName
    Return jow

End Function

2 个答案:

答案 0 :(得分:0)

更改后,您将显式选择p.SimpleName而不是整个对象。您需要按如下方式修改视图:

<p><%= item %></p>

答案 1 :(得分:0)

因为在第二种情况下ViewData("ListFrontName")不再是IEnumerable<WhateverTheTypeOfSimpleTable>而是IEnumerable<string>

要修复此更改,请在视图中更改您的循环:

<%  For Each item As String In ViewData("ListFrontName")%>
    <p><%=item%></p>
<%Next%>