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

丶灬走出姿态 提交于 2019-12-23 04:04:29

问题


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.



来源:https://stackoverflow.com/questions/24494718/how-to-display-a-collection-in-view-of-asp-net-mvc-razor-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!