tags:

views:

99

answers:

3

I have a generic list List<T> and I want to create a view that iterates the list and spits out the output.

I'm coming up against a couple of issues:

  • I don't know how to get my view.aspx to understand T
  • I don't know how to get it to render the correct partial for T

For instance, if I pass in a list of CustomObject1 then I want to render the partial CustomObject1.ascx and if I pass in a list of CustomObject2 the I want to render the partial CustomObject2.ascx.

Is there a simple way to do this that I've overlooked? I don't want to have a different aspx for every type of list I want to use, I'm just generating a of items after all. So it's a waste to have 15 different views to cover each type of list I'm going to need to use.

Any ideas or solutions would be gratefully received.

+1  A: 

Sounds to me that you first need to be using an Interface which is common to all your CustomObjects. Your View would then be base on List<IMyCommonInterface>.

As to including the correct ascx I'm not sure how even the generic system would solve this.

There are two approaches I can think of.

  • Have ICommonInterface expose a property that specifies the custom control to use. Simple but somehow feels all wrong and dirty.
  • Create an Attribute class that can be used to decorate the CustomObject classes, this attribute specifies the custom control to use. More complex because it requires a little reflection to discover the value of the attribute but somehow feels right and clean.
AnthonyWJones
+1  A: 

If your names are always going to match (CustomObject1 then I want to render the partial CustomObject1.ascx), then you could use the type name. So:

void MyMethod(List<T> items)
{
    foreach(T item in items)
    {
     Html.RenderPartial(item.GetType().Name, item);
    }
}
John MacIntyre
+2  A: 

Example of Anthony's first answer: make the list contents responsible for rendering themselves by e.g.

interface IHtmlRenderable { void RenderHtml(); }

void MyMethod(List items) //where T implements IHtmlRenderable { foreach(T item in items) ((IHtmlRenderable)item).RenderHtml(); }

But John's answer seems cleaner because you don't need to spend effort implementing this interface on each of your classes - or adding attributes etc.

Tim Lovell-Smith