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

后端 未结 5 1057
清歌不尽
清歌不尽 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:55

    I'd create an HtmlHelper extension that did this. Here's some pseudocode that looks shockingly like c# and may actually work:

    public static void TemplatedList(this HtmlHelper me, IEnumerable items, 
    IDictionary> templates)
    {
      foreach(var item in items)
      {
        var template = templates[item.GetType()];
        if(template != null) template(item);
      }
    }
    

    I'd use it like this:

    <% HtmlHelper.TemplatedList(ViewData.Model, new Dictionary
      {
        {typeof(GigSummary), x => %>
    
    
    SUP! GIG ANNOUNCEMENT FOR <%= x.Band %>!! What: <%= x.Title %> When: <%= x.Created %> Who: <%= x.Author %>
    <%} // add more type/template pairs here }); %>

提交回复
热议问题