Schotime
Schotime

Reputation: 15997

Inheriting from ViewPage

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

Upvotes: 4

Views: 1813

Answers (3)

Luke Smith
Luke Smith

Reputation: 24254

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.

Upvotes: 0

Simon Farrow
Simon Farrow

Reputation: 1921

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.

Upvotes: 1

Todd Smith
Todd Smith

Reputation: 17282

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>
{
}

Upvotes: 3

Related Questions