Reputation: 3488
I've written a web page with ~20 functions, and I just realized I need to utilize the same functions again in another page. is there any way to create one file that could be included in both webpages so that I could access my functions from both pages?
Thanks!
Upvotes: 0
Views: 728
Reputation: 3365
First check if some of these methods are suitable to be used as static methods
- a simplest check is if they use any class variables. If they don't use class variables they can be converted to static methods.
If some methods are suitable to be converted to static methods, you can move these in a static class and call them from anywhere in your project.
For methods that need to be instance methods, create your own base page class
and then inherit from this base class all the related pages.
public class BasePage : Page
{
}
public class WebPage1: BasePage
{
}
...and so on.
Edit 2:
public abstract class BasePage : Page
{
protected virtual string GetQueryStringValue(string name)
{
// add check to see if name is not null.
return Request.QueryString[name];
}
}
public partial class _Default : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
string name = GetQueryStringValue("name");
}
}
Upvotes: 1
Reputation:
You can create a generic functions in a class library project compile it as dll. Use it as reference in as much as file and as much as project. This is one of the reason why we have class library project given.
public class YourClass
{
public void Method()
{
// logic;
}
}
Aspx Page:
using Namespace.YourClass;
somewhere in code;
YouClass cls = New YourClass();
cls.Method();
Call it in as much as aspx.cs files.
Also if are not comfortable with class library projects then you can use the BasePage and Inheriting Page as suggested by Sridhar and Novide. It is used in website generally, i belive, in web applications I generally prefer try creating a CommonForAll / reusable method for the same
Upvotes: 0
Reputation: 656
If those are 20 functions related to UI... You can use Inheritance
.
Create a Base class inheriting from .Net Page
, say call it as BasePage
and put the reusable 20 functions there. Inherit all your UI pages from that, you will get all the 20 function available in all pages.
Upvotes: 0