Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show a list from a model in MVC razor

Can I enumerate a list from the model in the razor?

My model:

public class PreapprovalViewModel
{
    public int ProjectId { get; set; }
    public int Decision { get; set; }
    public List<BranchHead> BranchHeads { get; set; }
    public List<SelectListItem> Decisions { get; set; }
}

On the index for Preapproval I want a table that shows some fields within the BranchHead list.

Razor:

@model Mars.Intranet.ViewModels.PreapprovalViewModel
@{
    ViewBag.Title = "Index";
}
@Html.Partial("_ProjectPartial")
<h2>Preapproval</h2>
@using (Html.BeginForm()) {
    <div>
        Approve research request:
        @Html.DropDownListFor(o => o.Decision, Model.Decisions)
    </div>
    <div id="assign-branch-head" style="display: none;">
        Assign branch heads
        <table>
            <tr>
                <th>@Html.DisplayFor(o => o.BranchHeads.BranchName</th> <!-- Can I access the list in the model like this?-->
                <th>@Html.DisplayFor(o => p.BranchHeads.FirstName</th> <!-- Can I access the list in the model like this?-->
                <th>@Html.DisplayFor(o => p.BranchHeads.Comment</th> <!-- Can I access the list in the model like this?-->
            </tr> 
            <tr>
                <td><!-- I want the info from the list in model here--></td>
                <td><!-- I want the info from the list in model here--></td>
                <td><!-- I want the info from the list in model here--></td>
            </tr>
        </table>
    </div>
    <div class="approval-comment">
        Comment:
        @Html.TextAreaFor(o => o.Comment)
    </div>
    <button type="submit" class="btn_submit"></button>
}
like image 313
Carel Avatar asked Dec 15 '22 01:12

Carel


1 Answers

Yes, this is totally possible. But since this is a List<T> you need to iterate over it in order to display the data.

Just wrap your data in a foreach loop

@foreach (var item in Model.BranchHeads)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.BranchName)<br/>                    
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)<br/>                    
        </td>
        <td>                 
            @Html.DisplayFor(modelItem => item.Comment)<br/>
        </td>

    </tr>
}

In addition, you might want to use Html.DisplayNameFor() to display the table headers.

like image 81
Marco Avatar answered Dec 22 '22 00:12

Marco