ASP.NET MVC 3: Output specific view for concrete implementation

余生长醉 提交于 2019-12-04 16:56:08

Instead of the ugly foreach simply use display templates:

@model IEnumerable<SomeBaseViewModel>
<ul>
    @Html.DisplayForModel()
</ul>

and then define display templates for all child types. For example:

~/Views/Shared/DisplayTemplates/PointImpl.cshtml:

@model PointImpl
<li class="points">
    Points - @Model.Name - @Model.Points points 
    <a href="#">Remove</a>
</li>

and: ~/Views/Shared/DisplayTemplates/MediaImpl.cshtml:

@model MediaImpl
<li class="media">
    Media - @Model.Name - @Model.FileName 
    <a href="#">Remove</a>
</li>

See, no more ifs, no more loops, no more vars. Everything works by convention (templates must be situated in the ~/Views/Shared/DisplayTemplates or ~/Views/SomeController/DisplayTemplates folder and should be named as the name of the concrete type - PointImpl.cshtml, MediaImpl.cshtml, ...). Based on the concrete type the corresponding display template will be rendered and this automatically for each element of the main model collection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!