Quoting by models can be a bit confusing to start with in MVC just because template helpers ( Html.DisplayFor and Html.EditorFor ) can be provided by templates that the assistant will automatically call for each item in the collection. This means that if you are new to MVC and you do not understand that a DisplayTemplate or EditorTemplate has not already been provided for the collection, it looks as simple as that:
@Html.DisplayFor(m => m.SomePropertyThatHoldsACollection)
- thatβs all you need. Therefore, if you have already seen something like this, it is possible, therefore, you made the assumption that this will work. However, suppose for a moment that a template has not been provided. You have two options.
First, the easiest way would be to use foreach over the collection:
@foreach (var post in Model.PostsObject) { @Html.DisplayFor(m => post.PostTitle) // display other properties }
You can also use a for loop, but with IEnumerable<T> there is no indexer, so this will not work:
@for (int i = 0; i < Model.PostsObject.Count(); i++) { // This generates a compile-time error because // the index post[i] does not exist. // This syntax would work for a List<T> though. @Html.DisplayFor(m => post[i].PostTitle) // display other properties }
If you still want to use the for loop, you can use it like this:
@for (int i = 0; i < Model.PostsObject.Count(); i++) {
So use what you prefer. However, at some point it would be nice to learn patterns for your types . (Note: Although this article was written for MVC 2, the tip still applies.) They allow you to remove the loop logic from your views, while keeping them cleaner. In combination with Html.DisplayFor or Html.EditorFor they will also generate the correct element name to bind to the model (which is great). They also allow you to reuse a presentation for a type.
One final comment I would make is that the names of your properties are a bit detailed:
public class ModelMix { public IEnumerable<Posts> PostsObject { get; set; } public IEnumerable<Album> ThreadsObject { get; set; } }
We already know that these are objects, so there is no need to add them to the end. This is more readable:
public class ModelMix { public IEnumerable<Posts> Posts { get; set; } public IEnumerable<Album> Threads { get; set; } }