.net – ASP.NET MVC2 – Custom properties on a ViewPage – Education Career Blog

What I thought should be a fairly simple search, turned out to be alot more.

Atm I’m using a baseclass(MasterModel) for all my Models, that then get passed down from the ViewPage< HomeIndexModel > to the ViewMasterPage< MasterModel > and everything works fine. This was done this way after reading a post by “Scott Gu”.

Then I thought about inheriting from the ViewPage and extending the Factory or where ever the ViewPage is built from … but then I got lost.

Who is responsible for instantiating the ViewPage, ViewMasterPage and ViewUserControl.

The problem is more or less that I’m using an instance of the same class on 99% of all pages and always on the MasterPage, so its a pain to keep passing it around in the model all the time.

Is this even the right way to go or do you guys have any other suggestions ?

Update

I need to be able to inject complex types taken from my IOC ( StructureMap ) into the constructor of the ViewPage, so it will be easy to change the implementation. Thats why I’m looking for the place where the ViewPage gets constructed.

,

Are you able to look at using MVC3? Dependency injection into view pages is not possible because the creation is buried deep inside the implementation of the view engine.

This is now addressed in MVC3. Full Details: http://bradwilson.typepad.com/blog/2010/07/service-location-pt3-views.html

,

As I understand it, you are responsible, because within the definition of your View you specifically state what is the base class of your view.

Try this:

public sealed class MyViewPage : System.Web.Mvc.ViewPage
{
  public string Herp {get{return "Derp";}}
}

and, in your view, do this:

<%@ Page Language="C#" Inherits="MyApplication.MyViewPage" %>
<!-- compare the Inherits attribute in your standard View page -->
<%: Herp %>

I’ve never done this, but I’m 90% sure it would work. You would also need to do a generic version as well:

public sealed class MyViewPage<T> : System.Web.Mvc.ViewPage<T> {}

,

I’d ditch the base view model and DI into ViewPage to use composition (via ViewData) instead because it allows you a lot more flexibility than inheritance of view models. Imagine if you later wanted to add more components (header, menus, sidebar, user profile widget, etc) to various pages. If you have to fit all that into your base view model it’s going to get crowded and you probably won’t even need everything on every view. I use the model purely for the specific view being rendered and then put my other components into ViewData. Sample view code:

<% var headerModel = ViewDataConstants.HeaderData as HeaderViewModel %>

Or the super easy solution: have you considered just using ObjectFactory in your view? (This would make some people –myself included– cringe, but it does work.)

ObjectFactory.GetInstance<IService>();

Leave a Comment