在MVC剃刀中显示模型列表

Car*_*rel 3 html asp.net-mvc list razor

我可以从剃刀中的模型中列举一个列表吗?

我的模特:

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; }
}
Run Code Online (Sandbox Code Playgroud)

在Preapproval的索引上,我想要一个显示BranchHead列表中某些字段的表.

剃刀:

@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>
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*rco 10

是的,这完全有可能.但是因为这是一个List<T>你需要迭代它以显示数据.

只需将数据包装在foreach循环中

@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>
}
Run Code Online (Sandbox Code Playgroud)

此外,您可能希望Html.DisplayNameFor()用于显示表头.