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/Shared/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 oneMailListViewModelfor every result in the query. Your view is expecting only a singleMailListViewModel.You should update your view to expect
IEnumerable<MailListViewModel>, like so:Also, once you’ve done that you shouldn’t cast the
ModeltoIEnumerableas that will result in each item in the enumeration being treated as typeobjectso it will appear as though none of your properties exist.