【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>

 

能實現同樣的效果

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章