尝试在ASP.NET MVC中呈现局部视图时,我收到以下错误.我是ASP.NET MVC的新手,我确信错误很简单,只是因为我缺乏完全的理解.
问题(对于那些不想阅读一切的人):
是什么导致这个错误?
Exception Details:
System.InvalidOperationException
:
The model item passed into the
dictionary is of type
'MyApp.Models.ClassroomFormviewmodel'
but this dictionary requires a model
item of type
'System.Collections.Generic.IEnumerable
1[MyApp.Models.ClassroomFormviewmodel]’`.
的entites
我有两个具有父/子关系的实体.
Classroom StickyNote ------------ ----------- Id 1 ----- Id Name \ Name (...) \ Content ---- * ClassroomID
模型
在模型中,StickyNote内容保存在不同的表中,并通过以下方法访问(使用Linq-to-sql)
public IQueryable<StickyNote> GetStickyNotesByClassroom(Classroom classroom) { return from stickynote in db.StickyNotes where stickynote.ClassroomID == classroom.ID select stickynote; }
我已经创建了一个局部视图来显示StickyNote的内容,因为它属于它的教室.我遇到的问题是我无法让它显示,并收到以下错误:
The model item passed into the
dictionary is of type:
'MyApp.Models.ClassroomFormviewmodel'
but this dictionary requires a model
item of type
'System.Collections.Generic.IEnumerable
1[MyApp.Models.ClassroomFormviewmodel]’`.
Description: An unhandled exception
occurred during the execution of the
current web request. Please review the
stack trace for more information about
the error and where it originated in
the code.Exception Details:
System.InvalidOperationException
:
The model item passed into the
dictionary is of type
'MyApp.Models.ClassroomFormviewmodel'
but this dictionary requires a model
item of type
'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>
父视图
而来自其他View的代码调用它:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits= "System.Web.Mvc.ViewPage<MyApp.Models.ClassroomFormviewmodel>" %> {...} <% Html.RenderPartial("StickyNotes",Model); %>
解决方法
将您的PartialView中的声明更改为
Inherits=" System.Web.Mvc.ViewUserControl<MyApp.Models.ClassroomFormviewmodel>"
要么
你真正想要的(真正看你的代码)是一个IEnumerable< ClassroomFormviewmodel>
所以您的呼叫页面中的模型需要是IEnumerable< ClassroomFormviewmodel>
从本质上讲,你正在努力做到这一点
public void Render(ClassroomFormviewmodel model) { RenderPartial(model) //Cannot cast single instance into an IEnumerable } public string RenderPartial(IEnumerable<ClassroomFormviewmodel> model) { //Do something }