【问题标题】:Show a list from a model in MVC razor在 MVC razor 中显示模型的列表
【发布时间】:2014-02-18 11:47:00
【问题描述】:

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

我的模特:

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; }
}

在 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>
}

【问题讨论】:

    标签: html asp.net-mvc list razor


    【解决方案1】:

    是的,这是完全可能的。但由于这是List&lt;T&gt;,您需要对其进行迭代才能显示数据。

    只需将数据包装在 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>
    }
    

    此外,您可能希望使用Html.DisplayNameFor() 来显示表格标题。

    【讨论】:

    • 是的,这看起来正是我所需要的。谢谢
    猜你喜欢
    • 2020-11-23
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    相关资源
    最近更新 更多