views:

592

answers:

4

Is it possible to inherit from both ViewPage and ViewPage<T>?? Or do I have to implement both. Currently this is what I have for ViewPage. Do i need to repeat myself and do the same for ViewPage<T>??

    public class BaseViewPage : ViewPage
    {
        public bool LoggedIn
        {
            get
            {
                if (ViewContext.Controller is BaseController)
                    return ((BaseController)ViewContext.Controller).LoggedOn;
                else
                    return false;
            }
        }
    }
A: 

I want to have the LoggedIn property whether or not i'm in a strongly typed view or not.

If I inherit from ViewPage<T> then BaseView page throws an error cause it needs to be BaseView<T> etc.

Schotime
+1  A: 

Create both versions:

public class BaseViewPage : ViewPage
{
     // put your custom code here
}

public class BaseViewPage<TModel> : BaseViewPage where TModel : class
{
    // code borrowed from MVC source

    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);
    }
}

then

public class MyCustomView : BaseViewPage
{
}

or

public class MyCustomView : BaseViewPage<MyCustomViewData>
{
}
Todd Smith
Doesn't that mean i would have to repeat the same property 'LoggedIn' code in each one. Surely I shouldn't have to repeat myself.
Schotime
That seems to work. Thanks. I thought about copying that code but then it still didn't seem right that I would have to.
Schotime
+1  A: 

Depending on how you are doing things you might want to look at

ViewContext.HttpContext.Request.IsAuthenticated

it might save you some time instead of extending the ViewPage class.

If there is some other data that you are after you could maybe write an extension method to one of the classes that provides the data. E.g. if LoggedIn was stored in the session you could extend the context to give you an IsLoggedIn() in method.

Edit:

As your extending a class that is already available in the both the base and strongly typed view it will be available in both. The only other way around is to reimplement the strongly typed version as above.

Simon Farrow
A: 

I wouldn't put this in the View, instead I'd have it as a property on the ViewModel (have a BaseViewModel). It will be easier to test as well as ensuring you're not going down the slope of putting business logic into the views.

Luke Smith