2

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
  • I decided to change my approach.. Making use of MasterPage for main part of view, extending each particular view. Using abstract view model for master page, forcing child pages to give the master page necessary data. Commented May 28, 2010 at 14:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.