How to display a collection in View of ASP.NET MVC Razor project?
My Model and View is below. For one person i've to display Many tests on the screen. Thanks in Advance
namespace UI.Models
{
public class SuperStudent
{
public string FullName { get; set; }
public ICollection<TestDetail> CandidateTestDetails { get; set; }
}
public class TestDetail
{
public DateTime TestDate { get; set; }
public string RegNum { get; set; }
}
}
View
@model IEnumerable<UI.Models.SuperStudent>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.FullName)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
Print all test details
</td>
</tr>
}
</table>
For one person your view must be like :
The code works the same inside a loop as it does outside the loop. Just reference the loop item. For example:
That would output just the
RegNum
value. You can also make use of things likeDisplayNameFor
by referencing an element in the collection:While intuitively it may seem that this could fail if
Model
is empty (sinceFirst()
would throw an exception), it doesn't actually executeFirst()
on the collection. The engine simply uses that to reflect into the model returned byFirst()
to determine the display name.Given this, you can construct the markup however you wish for those items. If it's complex enough, you might even create a partial view for just an item in that collection and render that partial view in the loop by passing the
item
value to the partial view.