Calling a function from another page in C #

I want to call some public page method from another page

Here is my code

public class FirstPage : Page { public string Connect() { // method code here } // etc... } 

It throws an error when calling this method from another page

+4
source share
4 answers

If this method is common to both pages, consider using a base class for the page that inherits from the page. The method can go there.

 public YourPage: BaseClass { public void MyMethod() { base.BaseMethod(); } } public BaseClass: System.Web.UI.Page { //.. your shared method goes here protected BaseMethod() { //.. logic here } } 

This makes sense if your pages have the same functional area, for example. they all relate to order processing

+5
source

This is not a good practice. If both pages want to share this method, you can put them in another library of classes / classes and create an instance and call it from both pages.

The approach you will use is determined by the nature of the method; consider the context. If we are in the context of Page , then it’s best to think that the functionality here should be related to the actions that should be performed on the page, that is, the view (GUI rendering).

If functionality is associated with a view, consider using a common class or a common base class .

In this question, the sharing method is Connect β€” if it connects to a service or database for data, then consider encapsulating this code as an additional library; this library can be reused in several projects (regardless of the display style), and the logic will be independent of the display; eg:

 public partial class MyCodeBehindCS : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { MyNamespace.MyCustomClass myClass = new MyNamespace.MyCustomClass(); myClass.Connect(); var myResult = myClass.DoSomething(); } } 

Then you can do whatever you want with myResult.

+2
source

Your approach is 100% incorrect. Please regroup the code and find another way to implement your task.

What you can do to split a method between multiple pages is to implement your own page class

 public class FirstPage : YourCustomPageClass { public string A() { return this.YourCUstomPageCLassMethod(); } // etc... } public class SecondPage : YourCustomPageClass { public string B() { return this.YourCUstomPageCLassMethod(); } // etc... } 

Look here and here.

+1
source

On the second page, enter the code that you can access the first functions of the page

 <%@ Reference Page="~/page1.aspx" %> 

Now you can call functions to read the first page

  page1.func1(); 

or

 page1 a=new page1(); a.func1(); 
-2
source

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


All Articles