Dean.DePue
Dean.DePue

Reputation: 1013

Header row for editorfor template

I have a view in MVC4 that looks like this:

 @model List<Home.Models.Model>
@{
ViewBag.Title = "DPR";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("AgendaNotes", "Home", FormMethod.Post, new    { @id = "formDPR"}))
{
<table style="font-size:xx-small">
    <thead>
        <tr>
            <th>Name</th>
            <th>DOD ID</th>
            <th>Last Review</th>
            <th>Include?</th>
            <th>Reason</th>
            <th>Notes</th>
        </tr>
    </thead>
</table>
<div style="background-color:white">
    @Html.EditorForModel()
</div>
<div>

</div>
}

And the model.cshtml is simply some of the fields in a single row. I don't want to put headers on that single row as they are repeated as many times as their are in the list. Is there a simple way to make a header for the rows of the model in the editorfor template?

This is how I did it:

 <table style="font-size:xx-small" class="table_body">
        <thead>
            <tr>
                <th>Name</th>
                <th>DOD ID</th>
                <th>Last Review</th>
                <th>Include?</th>
                <th>Reason</th>
                <th>Notes</th>
            </tr>
        </thead>
        @for (var i = 0; i < Model.Count; i++)
        {
            <tr>
                @Html.EditorFor(m=>Model[i])
            </tr>
        }
    </table>

And in the model.cshtml it simple some of the fields each in a TD element.

Upvotes: 0

Views: 391

Answers (1)

Captain0
Captain0

Reputation: 2623

Not 100% sure that I understand you correctly. Create the table header in the view, then call the EditorTemplate in a for each

@using (Html.BeginForm("AgendaNotes", "Home", FormMethod.Post, new { @id = "formDPR" }))
{
  <table style="font-size:xx-small">
    <thead>
        <tr>
            <th>Name</th>
            <th>DOD ID</th>
            <th>Last Review</th>
            <th>Include?</th>
            <th>Reason</th>
            <th>Notes</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.Details)
        {
            @testTemplate(item)
        }
    </tbody>
  </table>
}

Then change the editor template to be for only one row eg.

@helper testTemplate(Details detail)
{
  <tr>
    <td>@detail.Propery1</td>
    <td>@detail.Propery2</td>
  </tr>
}

I used an inline helper just to illustrate what I mean. Now you should have a table with one header and lots of rows

Upvotes: 1

Related Questions