views:

57

answers:

1

I have an ASP.NET MVC application which I want to dynamically pick the partial view and what data gets passed to it, while maintaining strong types.

So, in the main form, I want a class that has a view model that contains a generically typed property which should contain the data for the partial view's view model.

public class MainViewModel<T>
{
    public T PartialViewsViewModel { get; set; }
}

In the User Control, I would like something like:

Inherits="System.Web.Mvc.ViewUserControl<MainViewModel<ParticularViewModel>>" %>

Though in my parent form, I must put

Inherits="System.Web.Mvc.ViewPage<MainViewModel<ParticularViewModel>>" %>

for it to work.

Is there a way to work around this? The use case is to make the user control pluggable. I understand that I could inherit a base class, but that would put me back to having something like a dictionary instead of a typed view model.

+1  A: 

You can use the DisplayTemplates and EditorTemplates to accomplish this. So if I'm reading your question right, you have a setup like this:

If you are using .NET 4.0 (yay for covariant generics!)

System.Web.Mvc.ViewPage<MainViewModel<object>>

If you are using .NET 3.5:

System.Web.Mvc.ViewPage<MainViewModel<object>>

public class MainViewModel
{
    public object PartialViewsViewModel { get; set; }
}

You can then invoke DisplayFor on that object to get a partial view. So invoking:

<%= Html.DisplayFor(m => m.PartialViewsViewModel) %>

Will look for a template in your DisplayTemplates folder for a skin of the name of your type. So if you have a ParticularViewModel.ascx in your DisplayTemplates, it will use that control as the 'partial view'. If you were using some other kind of view model type, then search for OtherViewModel.ascx (for example).

The template for ParticularViewModel.ascx would then have:

System.Web.Mvc.ViewUserControl<ParticularViewModel>

Which lets you treat the object as a strongly typed model.

Tejs