简体   繁体   中英

referencing one aspx.cs class in another aspx.cs class?

有谁知道如何重用另一个aspx页面中一个aspx.cs类中的代码?

这完全取决于您最终要做什么,但是一种选择是在App_Code文件夹中构建一个可重用的类,并在整个站点中使用它。

Ideally you should put your reusable methods in a seperate class in a seperate cs file.

But what you are asking for can also be easily done, here is an example:

Page1.aspx.cs

 public partial class MyPage1: System.Web.UI.Page
    {

        public static void MyTestFunction()
        {
            //Code Here           

        }

        public void MyTestFunction2()
        {
            //Code Here
        }
}

Page2.aspx.cs

    public partial class MyPage2: System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
           MyPage1.MyTestFunction();  // static function call

           //or

           MyPage1 page1 = new MyPage1();
           page1.MyTestFunction2();           


        }

      }

There are several options for reuse in ASP.NET:

  • Master pages
  • user controls
  • composite controls
  • create a custom class which inherits from the Page class and have your pages inherit from that custom class
  • Create a helper class which has reusable methods which you can use in your different webforms

Reusing code in multiple pages should be done in a separate class as mentioned or by using another mechanism such as master pages, etc. Trying to call code from multiple aspx pages without using backend classes is risky going forward with upgrades as it makes your app more brittle and harder to maintain over time. frontend pages such as ASPX pages should contain their own independent codebehind only. They should not reference another ASPX page. A better model is to set up an object model prior to the GUI layer, then call into the object model from various pages. That way, the page code is responsible only for it's own local page elements and any business logic needed across pages is housed elsewhere. Again, if you need UI logic to be shared, use something like old-style include files, master pages, or user controls which can be very useful at sharing as well as separating out the concerns of each piece (that separation of concerns principle is very important and when done right can help your app remain clean and easy to upgrade later!)

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