简体   繁体   中英

MVC DisplayFor template table with duplicated headers

Using a EditorFor template and trying to create a table, how can I get only one header row instead of one for each item of the collection?

Being the viewmodel

public class CashbackOfferViewModel
{
    public List<SingleCashbackOfferViewModel> Offers { get; set; }
}

In the view I have

@Html.DisplayFor(m => m.Offers)

And the display template is

@using LMS.MVC.Infrastructure
@model LMS.MVC.Areas.Finance.Models.SingleCashbackOfferViewModel
<table class="dataGrid">
    <thead>
        <tr class="headerRow">
            <th>@Html.LabelFor(m => m.CampaignName)</th>  
            <th>@Html.LabelFor(m => m.PersonId)</th>
            <th>@Html.LabelFor(m => m.FullName)</ths>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>@Html.DisplayFor(m => m.CampaignName)</td>
            <td>@Html.DisplayFor(m => m.PersonId)</td>
            <td>@Html.DisplayFor(m => m.FullName)</td>          
        </tr>
    </tbody>
</table>

One solution can be:

Create display template for your whole model

@using LMS.MVC.Infrastructure
@model LMS.MVC.Areas.Finance.Models.CashbackOfferViewModel
<table class="dataGrid">
    <thead>
        <tr class="headerRow">
            <th>CampaignName</th>  
            <th>PersonId</th>
            <th>FullName</ths>
        </tr>
    </thead>
    <tbody>
        @for(int i = 0; i < Model.Offers.Count; ++i)
        {
        <tr>
            <td>@Html.DisplayFor(m => m.Offers[i].CampaignName)</td>
            <td>@Html.DisplayFor(m => m.Offers[i].PersonId)</td>
            <td>@Html.DisplayFor(m => m.Offers[i].FullName)</td>          
        </tr>
        }
    </tbody>
</table>

Also i think in your code, your model must be List of SingleCashbackOfferViewModel and you can easily iterate over the list and create table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM