Create an ASP.NET global function?

I think this is a pretty simple question ... How to make asp.net global function? For example, if I have a GetUserInfo () function defined in default.aspx, how can I call this function from mypage2.aspx?

+3
source share
5 answers

Another alternative is to create a base page class that inherits all of your pages:

public class BasePage : System.Web.UI.Page
{
     public string GetUserInfo()
     {...}

}

All aspx pages that need this method can inherit the BasePage class. Since BasePage inherits from System.Web.UI.Page, they will also have access to all the methods and properties of the page.

+14
source

"" , cProgram cApp. , .

public class cApp
{

             private readonly static string _Env = 
!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["GenMgrEnv"]) ? 
    System.Configuration.ConfigurationManager.AppSettings["GenMgrEnv"] : "Prod";


     public static string Env
    {
        get
        { return _Env; }
    }


    public static int version
    {
        get { return 3; }
    }


    public static string CurrentUser()
    {
        return (System.Web.HttpContext.Current.Request.Cookies["UID"] != null ? System.Web.HttpContext.Current.Request.Cookies["UID"].Value : "");

    }

    public static Guid UserId
    {
        get
        {
            if (System.Web.HttpContext.Current.Session["UserId"] == null)
            {
                loadUserIdentity();
            }
            return new Guid(System.Web.HttpContext.Current.Session["UserId"].ToString());
        }

    }



    public static Control FindControlRecursively(String id, Control parent)
    {
        if (parent == null)
            return null;

        foreach (Control control in parent.Controls)
        {
            if (control.ID == id)
                return control;

            Control child = FindControlRecursively(id, control);

            if (child != null)
                return child;
        }
        return null;
    }
}
+3

...

  • GetUserInfo() helper/utility
  • , GetUserInfo(), aspx .
+2

default.aspx (, , _Default). , GetUserInfo() , mypage2.aspx, :

_Default.GetUserInfo();

, . GetUserInfo() . - :

public static class Utilities
{
    public static string GetUserInfo()
    { ... }
}

Utilities.GetUserInfo();
+1

You can also create a static class in which you can place functions that can be called from anywhere.

static class MyClass {
   void MyFunction() {
   }
}

MyClass.MyFunction();

Or in VB:

Module MyModule
    Public Function MyFunction() 

    End Function
End Module

MyModule.MyFunction()
+1
source

Source: https://habr.com/ru/post/1742034/


All Articles