How to create a base class for pages and UserControl?

Base classes for the page and UserControl:

public class MyWebPage : System.Web.UI.Page { }

public class MyUserControl : System.Web.UI.UserControl { }

An assistant who can use any of them:

void SetSessionValue<T>(string key, T value) { Session[key] = value; }

How can I achieve something like the following?

public class WebObject // can't inherit from both Page and UserControl { 
   protected void SetSessionValue<T>(string key, T value) { 
      Session[key] = value; 
   }
}  

public class MyWebPage : WebObject { }

public class MyUserControl : WebObject { }

Update: I was excited that I hoped I could solve it, but, alas, it does not compile.

public class WebObject<T> : T
{
}
public class MyWebPage : WebObject<System.Web.UI.Page>
{
}
+5
source share
4 answers

. . . , , Page :

// Code in the MyUserControlBase class
public int SomeCommonMethod() {
    return ((MyBasePageType)this.Page).SomeCommonMethod();
}

, , , DI , - , . , , :)

+4

IIRC UserControl TemplateControl, .

+1

, , (, UserControl ).

- :

public class ApplicationContext
{
    // Private constructor to prevent instantiation except through Current property.
    private ApplicationContext() {}

    public static ApplicationContext Current
    {
        get
        {
            ApplicationContext current = 
                 HttpContext.Current.Items["AppContext"] as ApplicationContext;
            if (current = null)
            {
                current = new ApplicationContext();
                HttpContext.Current.Items["AppContext"] = current;
            }
            return current;
        }
    }

    public void SetSessionValue<T>(string key, T value) 
    { 
        HttpContext.Current.Session[key] = value; 
    }
    ... etc  ... 
}  

ApplicationContext , ApplicationContext.Current.SetSessionValue .

, , SetSessionValue , ,

public class ApplicationContext
{
    ... as above ...

    public ShoppingBasket ShoppingBasket
    {
        ShoppingBasket shoppingBasket = 
           HttpContext.Current.Session["Basket"] as ShoppingBasket;
        if (shoppingBasket == null)
        {
            shoppingBasket = ... e.g. retrieve from database
            HttpContext.Current.Session["Basket"] = shoppingBasket;
        }
        return shoppingBasket;
    }
}

, ShoppingBasket , , , - ApplicationContext.

+1
  • 1) , , , .
  • 2) UserControl Page Pre_Init Load
  • 3) .

.

0

All Articles