10

背景

尝试在 ASP.NET MVC 中呈现部分视图时收到以下错误。我是 ASP.NET MVC 的新手,我确信这个错误很容易解决,只是因为我缺乏完全的理解。

问题对于那些不想阅读所有内容的人):

是什么导致了这个错误?

异常详细信息:: System.InvalidOperationException传递到字典中的模型项是类型 'MyApp.Models.ClassroomFormViewModel' ,但此字典需要类型为 'System.Collections.Generic.IEnumerable1[MyApp.Models.ClassroomFormViewModel]'` 的模型项。


实体

我有两个具有父/子关系的实体。

课堂便笺
------------ -----------
编号 1 ----- 编号
姓名\姓名
(...) \ 内容
                     ---- * 教室ID

模型

ModelStickyNote 中的内容保存在不同的表中,并被访问(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.IEnumerable1[MyApp.Models.ClassroomFormViewModel]'` 的模型项。说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:: System.InvalidOperationException传递到字典中的模型项是类型 'MyApp.Models.ClassroomFormViewModel' ,但此字典需要类型为 'System.Collections.Generic.IEnumerable1[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">&nbsp;</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);
  %>
4

2 回答 2

8

您正在将 ClassroomFormViewModel 的单个实例传入,并且 View 期待一个集合,即IEnumerable<ClassroomFormViewModel>.

将您在 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
}
于 2009-07-09T14:19:32.327 回答
2

你的部分应该开始

<%@ Control Language="C#" Inherits="
System.Web.Mvc.ViewUserControl<MyApp.Models.ClassroomFormViewModel>" >

我猜你想在你的页面上显示一个教室。如果您想显示更多内容,请不要使用视图模型列表。使用具有教室列表的视图模型

于 2009-07-09T14:16:09.367 回答