views:

22

answers:

1

I try to inhering from ViewPage as shown in this question http://stackoverflow.com/questions/370500/inheriting-from-viewpage

But I get a

Compiler Error Message: CS1061: 'object' does not contain a definition for 'Spot' and no extension method 'Spot' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

My viewpage, normally I can do Model.ChildProperty(Spot) when I inherit from ViewPage directly, so I do that here too. But it fails.

 <%@ Page Language="C#" Inherits="Company.Site.ViewPageBase<WebSite.Models.SpotEntity>"  %>

    <h1><%= Html.Encode(Model.Spot.Title) %></h1>

To get it working correctly I have to do like this:

<%@ Page Language="C#" Inherits="Company.Site.ViewPageBase<WebSite.Models.SpotEntity>"  %>

    <h1><%= Html.Encode(((WebSite.Models.SpotEntity)Model).Spot.Title) %></h1>

Here is my classes:

namespace Company.Site
{
public class ViewPageBase<TModel> : Company.Site.ViewPageBase where TModel:class
{
    private ViewDataDictionary<TModel> _viewData;

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public new ViewDataDictionary<TModel> ViewData
    {
        get
        {
            if (_viewData == null)
            {
                SetViewData(new ViewDataDictionary<TModel>());
            }
            return _viewData;
        }
        set
        {
            SetViewData(value);
        }
    }

    protected override void SetViewData(ViewDataDictionary viewData)
    {
        _viewData = new ViewDataDictionary<TModel>(viewData);

        base.SetViewData(_viewData);
    }
}

public class ViewPageBase : System.Web.Mvc.ViewPage
{
}
}

So how do I get it to work without the explicit cast?

+1  A: 

Is there a reason you need ViewPageBase to derive from ViewPageBase? It doesn't look like ViewPageBase adds anything.

The simplest solution is to change ViewPageBase to derive from ViewPage, not from ViewPageBase. The Model property of ViewPageBase is of type object. The Model property of ViewPage is TModel (in other words, the type you specify).

If you absolutely must derive from ViewPageBase, you can try the following (this is the pattern that ViewPage uses:

public class ViewPageBase<TModel> : ViewPageBase {
    private ViewDataDictionary<TModel> _viewData;

    public new TModel Model {
        get {
            return ViewData.Model;
        }
    }

    public new ViewDataDictionary<TModel> ViewData {
        get {
            if (_viewData == null) {
                SetViewData(new ViewDataDictionary<TModel>());
            }
            return _viewData;
        }
        set {
            SetViewData(value);
        }
    }

    protected override void SetViewData(ViewDataDictionary viewData) {
        _viewData = new ViewDataDictionary<TModel>(viewData);

        base.SetViewData(_viewData);
    }
}
Haacked