Ben john Ben john - 2 months ago 6
C# Question

MVC view throws an error

I have a controller that return a List of Messages

public ActionResult MainMenu()
{
var myDataOp = new DataBaseOperations();
var Message=myDataOp.GetMessages();
return View(Message);
}


Here is the Function That gets the List

public List<ViewClass> GetMessages()
{
PrincelysDataContext pData = new PrincelysDataContext();
Princelys.Models.ViewClass myViewList =new ViewClass();
var myMessage =from r in pData.Messages select r;
DateTime presentTime = new DateTime();
foreach (var myValues in myMessage)
{
myViewList.myMessage.Add(new ViewClass
{
CreatedName ="ffff",// (from m in pData.Users where m.userid == myValues.createdBy select m.userName).Single(),
Messages = myValues.Message,
CreateOn = myValues.createddatetime.Subtract(presentTime)
});
}
return myViewList.myMessage;
}


I then use my list in the View Page.

@model Princelys.Models.ViewClass
....
@foreach (var messageValues in Model.myMessage)
{
<li class="left clearfix">
<span class="chat-img pull-left">
<img src="http://placehold.it/80/30a5ff/fff" alt="User Avatar" class="img-circle" />
</span>
<div class="chat-body clearfix">
<div class="header">
<strong class="primary-font">@messageValues.CreatedName</strong> <small class="text-muted">@messageValues.CreateOn.TotalHours mins ago</small>
</div>
<p>
@messageValues.Messages
</p>
</div>
</li>


}

I get an error when I run the view page on a browser


The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Princelys.Models.ViewClass]', but this dictionary requires a model item of type 'Princelys.Models.ViewClass'.


This is the class that hold the properties

public class ViewClass
{
public ViewClass()
{ myMessage = new List<ViewClass>(); }
public string CreatedName { get; set; }
public string Messages { get; set; }
public TimeSpan CreateOn { get; set; }
public List<ViewClass> myMessage;
}


This is my first MVC 5 project. Any help would be greatly appreciated.

Answer

You are returning List<ViewClass> in your controller action, however looks like your view is strongly typed with ViewClass. Change it to @model IEnumerable<ViewClass> Or other way round i.e. return ViewClas from controller.

Based on the comments the issue is GetMessages should return ViewClass so it should look like below

public ViewClass GetMessages()
{
    PrincelysDataContext pData = new PrincelysDataContext();
    Princelys.Models.ViewClass myViewList =new ViewClass();
    var myMessage =from r in pData.Messages select r;
    DateTime presentTime = new DateTime();
    foreach (var myValues in myMessage)
    {
        myViewList.myMessage.Add(new ViewClass
        {
            CreatedName ="ffff",// (from m in pData.Users where m.userid == myValues.createdBy select m.userName).Single(),
            Messages = myValues.Message,
            CreateOn = myValues.createddatetime.Subtract(presentTime)
        });
    }
    return myViewList;
}
Comments