背景
尝试在 ASP.NET MVC 中呈现部分视图时收到以下错误。我是 ASP.NET MVC 的新手,我确信这个错误很容易解决,只是因为我缺乏完全的理解。
问题(对于那些不想阅读所有内容的人):
是什么导致了这个错误?
异常详细信息::
System.InvalidOperationException
传递到字典中的模型项是类型'MyApp.Models.ClassroomFormViewModel'
,但此字典需要类型为'System.Collections.Generic.IEnumerable
1[MyApp.Models.ClassroomFormViewModel]'` 的模型项。
实体
我有两个具有父/子关系的实体。
课堂便笺 ------------ ----------- 编号 1 ----- 编号 姓名\姓名 (...) \ 内容 ---- * 教室ID
模型
在Model
StickyNote 中的内容保存在不同的表中,并被访问(Linq-to-SQL
通过以下方法使用:
public IQueryable<StickyNote> GetStickyNotesByClassroom(Classroom classroom)
{
return from stickynote in db.StickyNotes
where stickynote.ClassroomID == classroom.ID
select stickynote;
}
错误
我创建了一个用于显示StickyNote
内容的局部视图,因为它“属于”它所在的教室。我遇到的问题是我无法让它显示,并收到以下错误:
传入字典
'MyApp.Models.ClassroomFormViewModel'
的模型项的类型为:但此字典需要类型为'System.Collections.Generic.IEnumerable
1[MyApp.Models.ClassroomFormViewModel]'` 的模型项。说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。异常详细信息::
System.InvalidOperationException
传递到字典中的模型项是类型'MyApp.Models.ClassroomFormViewModel'
,但此字典需要类型为'System.Collections.Generic.IEnumerable
1[MyApp.Models.ClassroomFormViewModel]'` 的模型项。
局部视图
这是部分视图代码:
<%@ Control Language="C#" Inherits="
System.Web.Mvc.ViewUserControl<IEnumerable<MyApp.Models.ClassroomFormViewModel>>" %>
<table background="../../images/corkboard.jpg">
<% foreach (var items in Model) { %>
<tr>
<% foreach (var item in items.StickyNotes) { %>
<td><div class="sticky_note_container">
<!-- actually use a post it note here on the page -->
<div class="sticky_note">
<div class="sticky_note_content">
<!-- content of sticky note here -->
<% Html.ActionLink(item.Name, "ShowStickyNoteContent"); %>
<!-- end of content of sticky note -->
</div>
</div>
<div class="sticky_note_footer"> </div>
<br clear="all" />
</div>
</td>
<% } %>
</tr>
<% } %>
</table>
父视图
以及调用它的另一个视图中的代码:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits=
"System.Web.Mvc.ViewPage<MyApp.Models.ClassroomFormViewModel>" %>
{...}
<%
Html.RenderPartial("StickyNotes", Model);
%>