Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ISummary {
  Guid Id {get;set;}
  string Title {get;set;}
  DateTime Created {get;set;}
}

public class GigSummary: ISummary {
 Guid Id {get;set;}
 string Title {get;set;}
 DateTime Created {get;set;}
 string VenueName {get;set}
 string Band {get;set;}
}

public class NewsSummary: ISummary {
 Guid Id {get;set;}
 string Title {get;set;}
 DateTime Created {get;set;}
 string Author{get;set}
}

I now pass this list of Gigs and News Summary objects (as a list of ISummary) to the view as the model.

I want to render this list using a different partial for each type contained in the list.

How can I do this is ASP.NET MVC?

like image 554
iasksillyquestions Avatar asked Jun 05 '09 13:06

iasksillyquestions


1 Answers

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.

like image 192
Lewis Avatar answered Sep 28 '22 03:09

Lewis