简体   繁体   中英

How to call a function in more than one page in asp.net (C#)?

I have three different .aspx pages (abc1.aspx,abc2.aspx,abc3.aspx). Now I want to call one function func() in three of them. I want to define the definition of a function only 1 time and call it on 3 different pages.

Create base class that inherits from System.Web.UI.Page . Define your function there. Then inherit from this base page instead of System.Web.UI.Page in those aspx pages. After this you can call the function from any of those pages like so: base.MyFunct()

BasePage.cs

public abstract class BasePage : System.Web.UI.Page
{
    protected void MyFunct()
    {
    }
 }

Page1.aspx.cs, Page2.aspx.cs, Page3.aspx.cs

public partial class Page1 : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        base.MyFunct();
    }
}

public partial class Page2 : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        base.MyFunct();
    }
}

public partial class Page3 : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        base.MyFunct();
    }
}

Add a .cs or .vb class file to your website appCode folder. Define your function in that code file Example:

Class myFunctions
{
      public static int Sum(int a,int b)
      {
           return a+b;
      }
}

Now on your aspx code behind create an object of this class and use the function

int result = myFunctions.Sum(5,6);

Create a public class (optionally static) and add your method as a public static method to that class:

public class Utilities
{
  public static string DoStuff()
  {
    return "hello world";
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM