View and Master Page must inherit from same type

Last post 04-01-2008 4:59 AM by rjcox. 1 replies.

Sort Posts:

  • View and Master Page must inherit from same type

    03-31-2008, 1:15 PM
    • Member
      1 point Member
    • netstruc65
    • Member since 03-10-2008, 10:13 PM
    • Posts 8

    I have several views that use different view data types. However, they all use the same master page. I thought I could derive the different view data types from a base class, and then derive the master from that same base type, but the compiler doesn't like it.

     I am I using the wrong approach here? I could use an interface but then all the different view data types have to implement the same functionality. I'd like to use a base class to share the functionality.

  • Re: View and Master Page must inherit from same type

    04-01-2008, 4:59 AM
    • Contributor
      7,054 point Contributor
    • rjcox
    • Member since 12-19-2007, 9:14 AM
    • Basingstoke, UK
    • Posts 1,444

    I was expecting that to have been fixed in preview #2 (see http://forums.asp.net/t/1195178.aspx for CTP #1 workaround).

    Looking at the source for ViewMasterPage<ViewData> (from http://codeplex.com/aspnet): 

    public class ViewMasterPage<TViewData> : ViewMasterPage {
    public new TViewData ViewData {
    get {
    ViewPage<TViewData> viewPage = Page as ViewPage<TViewData>;
    if (viewPage == null) {
    throw new InvalidOperationException(String.Format(CultureInfo.CurrentUICulture, MvcResources.ViewMasterPage_RequiresViewPageTViewData));
    }
    return viewPage.ViewData;
    }
    }
    }

    This has been rewritten, but still does not handle the case where the type parameter of the master page is a base class of the type parameter of the page.

    I can't understand why there is an attempt to case the page, I would have expected a direct cast of the ViewData member of the ViewContext:

    public class ViewMasterPage<TViewData> : ViewMasterPage {
    public new TViewData ViewData {
    get {
    TViewData viewData = ViewContext.ViewData as TViewData;
    if (viewData == null) {
    throw new InvalidOperationException(String.Format(CultureInfo.CurrentUICulture, MvcResources.ViewMasterPage_RequiresViewPageTViewData));
    }
    return viewData;
    }
    }
    }

    You can either (a) modify the source and compile your own System.Web.Mvc.dll, or (b) create a shim class like in the thread above that fixes the ViewData property.

    Richard
    Filed under:
Page 1 of 1 (2 items)