【ASP.NET】DisplayForModel的用法

 

在View中显示一个列表信息,我们能这样写,用一个foreach循环展示信息

@model IEnumerable<Wang.OA.Model.UserInfo>

@{
    ViewBag.Title = "Index2";
}

<h2>Index2</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ShowName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Remark)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ModfiedOn)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.SubTime)
        </th>
        <th></th>
    </tr>
    @foreach (var item in Model)
    {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.ShowName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Remark)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.ModfiedOn)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.SubTime)
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                    @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.Id })
                </td>
            </tr>
    }
</table>

 

我们也可以同DisplayForModel

首先在对于的视图文件夹新建一个DisplayTemplates文件夹,在以Model为名新建一个UserInfo.cshtml文件

在UserInfo.cshtml文件中

@model Wang.OA.Model.UserInfo
<tr>
    <td>
        @Model.Name
    </td>
    <td>
        @Model.ShowName
    </td>
    <td>
        @Model.Remark
    </td>
    <td>
        @Model.ModfiedOn
    </td>
    <td>
        @Model.SubTime
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
        @Html.ActionLink("Details", "Details", new { id = Model.Id }) |
        @Html.ActionLink("Delete", "Delete", new { id = Model.Id })
    </td>
</tr>

然后在列表视图中,去掉foreach循环,添加    @Html.DisplayForModel()

@model IEnumerable<Wang.OA.Model.UserInfo>

@{
    ViewBag.Title = "Index2";
}

<h2>Index2</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ShowName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Remark)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ModfiedOn)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.SubTime)
        </th>
        <th></th>
    </tr>
    @Html.DisplayForModel()
</table>

 

能实现同样的效果

 

相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页