tags:

views:

35

answers:

1

If you have:

 System.Web.Mvc.ViewUserControl<T>

how do you access T at runtime?

I have a base class which I pass into

Html.RenderPartial("ViewName", BaseControlModel);

but I want to create another extension method such as

Html.RenderTypedPartial("ViewName", BaseControlModel);

such that in the context of ViewName.ascx my BaseControlModel is transformed into type T from the original declaration. I already have the code to transform BaseControlModel into the type I expect, it looks like this:

BaseControlModel.GetModel<T>();

but I want to invoke this inside RenderTypedPartial generically, instead of specifically requesting type T in my view.

10/5 update: I went ahead and copy pasted RenderPartial and FindPartialView into my own extension method from the source on CodePlex and the type I get for my IView reference is a WebFormView which doesn't have the type as a generic argument that I defined in my partial .ascx...

A: 
obj.GetType().GetGenericArguments()[0];

The Type itself has GetGenericArguments to extract exactly this, and you can make a generic type too through MakeGenericType.

http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx

EDIT: You can build a type like:

var type = typeof(ViewUserControl<>).MakeGenericType(..);
return Activator.CreateInstance(type, new object[] { }); //object[] is ctor parms
Brian
that's the easy part; the hard part is how do you get the reference to obj representing the ViewUserControl?
gazarsgo
Will post the response above.
Brian
i don't need an open type of ViewUserControl, I need the closed type defined by my .ascx. I did some more digging and it looks like I might be out of luck until the next version of MVC since it's still tightly coupled to the webforms rendering engine -- the BuildManager builtin is converting ViewUserControl to a WebFormView so I probably lose my type reference unless I create my own BuildManager...
gazarsgo