背景
我在尝试在ASP.NET MVC中呈现部分视图时收到以下错误。我是ASP.NET MVC的新手,确定该错误很容易解决,只是源于我对其不够完全理解。
问题(适用于不想阅读全部内容的人):
是什么导致了这个错误?
异常详细信息:
System.InvalidOperationException
:传递给字典的模型项类型为'MyApp.Models.ClassroomFormViewModel'
,但此字典需要类型为'System.Collections.Generic.IEnumerable
1[MyApp.Models.ClassroomFormViewModel]'`的模型项。
实体
我有两个具有父/子关系的实体。
Classroom StickyNote ------------ ----------- Id 1 ----- Id Name \ Name (...) \ Content ---- * ClassroomID
模型
在Model
中,StickyNote的Content保存在不同的表中,并通过以下方法访问(使用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);
%>