Robert Ross Robert Ross - 18 days ago 7
C# Question

Looping through object in mvc view?

I have the following code in my view :

@{
var i = 0;
var posts = Session["num"] as List<class_project.Models.Post>;
if (posts != null)
{
foreach (object item in posts)
{
<p>@item</p>

}
}
}


As a result of this I am getting : a couple of class_project.Models.Post strings.

How can I display my actual objects instead?
I tried with item.something, which doesn't really work.

Answer

Try using object type "class_project.Models.Post" or "var" on your foreach and properties on your template:

@{
    var i = 0;
    var posts = Session["num"] as List<class_project.Models.Post>;
    if (posts != null)
    {
        //foreach (class_project.Models.Post item in posts)
        //the same as "foreach (var item in posts)"
        foreach (var item in posts)
        {
             <p>@item.PropertyOne</p>
             <p>@item.PropertyTwo</p>
        }
    }
}