开发者

The model item passed into the dictionary is of type 'System.Data.Linq.DataQuery`1[Models.MailListViewModel]'

开发者 https://www.devze.com 2023-01-13 07:38 出处:网络
I am getting an error saying: The model item passed into the dictionary is of type \'System.Data.Linq.DataQuery`1[WebUI.Models.MailListViewModel]\', but this dictionary requires a model item of type

I am getting an error saying:

The model item passed into the dictionary is of type 'System.Data.Linq.DataQuery`1[WebUI.Models.MailListViewModel]', but this dictionary requires a model item of type 'WebUI.Models.MailListViewModel'.

This is in my controller:

public ViewResult List()
    { var mailToShow = from m in mailRepository.Mail
                         join p in profilesRepository.Profiles on m.SenderId equals p.ProfileId 
                         select new MailListViewModel
                                    {
                                        SenderId = m.SenderId,
                                        ProfileId = p.ProfileId,
                                        UserName = p.UserName,
                                        Subject = m.Subject
                                    }; 
       return View(mailToShow);
    }

This is in my MailListViewModel:

public class MailListViewModel
{        
    public int SenderId;
    public int ProfileId;
    public string UserName;
    public string Subject;
}

This is in my view:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shar开发者_开发问答ed/Site.Master" Inherits="System.Web.Mvc.ViewPage<WebUI.Models.MailListViewModel>" %>

<% foreach (var m in (IEnumerable)Model)
       { %>
    <tr>
        <td>
        </td>
        <td>TODO image</td>   
        <td>
        <%: Model.SenderId %></td>

        <td><%: Model.Subject%></td>
    </tr>
    <% } %>

The error message seems to be conflicting, saying that I am using the correct model.

What should I do?


Your query is returning an IQueryable<MailListViewModel>, essentially one MailListViewModel for every result in the query. Your view is expecting only a single MailListViewModel.

You should update your view to expect IEnumerable<MailListViewModel>, like so:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<System.Collections.Generic.IEnumerable<WebUI.Models.MailListViewModel>>" %>

Also, once you've done that you shouldn't cast the Model to IEnumerable as that will result in each item in the enumeration being treated as type object so it will appear as though none of your properties exist.

0

精彩评论

暂无评论...
验证码 换一张
取 消