Inheriting from ViewPage

2019-02-14 16:28发布

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

3条回答
Ridiculous、
2楼-- · 2019-02-14 16:52

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.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-02-14 16:53

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.

查看更多
三岁会撩人
4楼-- · 2019-02-14 17:05

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>
{
}
查看更多
登录 后发表回答