How to display a collection in View of ASP.NET MVC

2019-05-31 01:37发布

问题:

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>

回答1:

For one person your view must be like :

@model UI.Models.SuperStudent
<h2>@Model.FullName</h2>
<table class="table">
<tr>       
    <th>
       TestDate 
    </th>  
   <th>
       RegNum
    </th>   
</tr>
@foreach (var item in Model.CandidateTestDetails ) {
 <tr>
    <td>
     @item.TestDate             
    </td>
   <td>
     @item.RegNum
    </td>
</tr>
}
 </table>


回答2:

The code works the same inside a loop as it does outside the loop. Just reference the loop item. For example:

@foreach (var student in Model) {
  @foreach (var test in student.CandidateTestDetails) {
    <tr>
      <td>@test.RegNum</td>
    </tr>
  }
}

That would output just the RegNum value. You can also make use of things like DisplayNameFor by referencing an element in the collection:

@foreach (var student in Model) {
  @foreach (var test in student.CandidateTestDetails) {
    <tr>
      <td>
        @Html.DisplayNameFor(model => student.CandidateTestDetails.First().RegNum)<br />
        @test.RegNum
      </td>
    </tr>
  }
}

While intuitively it may seem that this could fail if Model is empty (since First() would throw an exception), it doesn't actually execute First() on the collection. The engine simply uses that to reflect into the model returned by First() 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.