2009-07-09 4 views
10

фонеРабота с частичным видом на ASP.NET MVC

Я получаю следующее сообщение об ошибке при попытке вынести частичное представление в 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 

Модель

В Model содержимого StickyNote хранится в другой таблице, и доступ к ним (с использованием Linq-to-SQL по следующему методу:

public IQueryable<StickyNote> GetStickyNotesByClassroom(Classroom classroom) 
{ 
    return from stickynote in db.StickyNotes 
      where stickynote.ClassroomID == classroom.ID 
      select stickynote; 
} 

Error

Я создал частичный вид f или отображение 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">&nbsp;</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); 
    %> 

ответ

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 
} 
2

Ваш парциальное должен начать

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

Я предполагаю, что вы хотите отобразить один класс на вас странице. Если вы хотите отобразить больше, не используйте список режимов просмотра. Используйте одну модель, имеющую список классных комнат

Смежные вопросы