views:

134

answers:

3

In my ASP.NET MVC project, I have a polymorphic collection that I wish to render - say, an IEnumerable<ISomething> where the individual items may be a mix of different implementations of ISomething.

I'd like that list rendered, where each concrete type renders according to its own template (perhaps a strongly typed ViewUserControl).

In WPF, I'd be able to specify DataTemplates that would automatically bind concrete types to specific templates. Can I do something similar in ASP.NET MVC?

Obviously, I can iterate through the list and attempt a cast using the is keyword and then use a lot of if statements to render the desired control, but I was hoping for something more elegant (like WPF).

A: 

I'm not sure if I get you fully, but, why don't you implement a method to your ISomething interface like render for example, which by contract will be implemented to all of your other concrete entities, and then iterate through each item in the polymorphic collection and call it.

Galilyou
Because that would mean that UI-specific code invades the ISomething inteface. However, your suggestion has merit on the level where I could define a new interface that encapsulates the objects and defines a View Model for each object, with an associated View identifier (like a method, as you suggested). This could work, but is still a bit clunky compared to WPF's way of doing it.
Mark Seemann
A: 

I had a similar issue and never found a "simple" answer. I had the benefit of knowing that all items in the list would render the same way so I created a decorator for ISomething, converted the list to IEnumerable using some code from the Umbrella project (http://umbrella.codeplex.com), and then extracted out the relevant pieces. Kinda like the following:

public interface ISomethingDecorator
{
  string Description { get; }
  string[] Actions { get; } 
}

public class BigSomethingDecorator : ISomethingDecorator { /* ... */ }
public class SmallSomethingDecorator : ISomethingDecorator { /* ... */ }

Then, as I said, I use the Umbrella project to convert from ISomething to ISomethingDecorator and returned IEnumerable to the View.

Don't know if it'll help you with what you're trying to do -- especially being a month late -- but I thought I'd let you know how I handled it. If you're displaying completely different formats, it probably won't do the trick but maybe it can get you a starting point.

andymeadows
A: 

I ended up with developing a solution myself - I have described it in DataTemplating In ASP.NET MVC.

Mark Seemann