ASP.net MVC - rendering a List containing different types, with a different view for each type

后端 未结 5 1043
清歌不尽
清歌不尽 2020-12-29 00:29

Imagine I have a list of objects that implement an interface called ISummary The objects within this list MAY have additional properties ie.

public interface         


        
5条回答
  •  时光取名叫无心
    2020-12-29 00:38

    The most obvious way I can think of would be to do something like:

        foreach(ISummary summ in listOfISummary) {
        Html.RenderPartial(String.Fomat("~/Views/Shared/{0}Renderer.ascx", summ.GetType.ToString()), summ, ViewData);%>
    }
    

    and create a strongly typed view with a naming convention, like NewsSummaryRenderer.ascx.

    I expect that you could move this out to a helper method though, but I'd add it to one of the existing helpers through an extension method rather than putting it in a code behind as suggested previously.

提交回复
热议问题