Reputation: 5426
At the moment my website project in asp.NET consists of 5 .aspx files. I have defined the same functions in every .aspx file. What I want is a way to create my own library/file of functions, which I could include in my .aspx scripts.
While searching for solution I've only found this Dynamically Including Files in ASP.NET Which is used to dynamically include HTML and client-side scripts in .aspx. So it's not what I need.
Upvotes: 5
Views: 5270
Reputation: 468
follow these 5 easy-peasy steps! to save tons of function re-writes between asp.net web forms!
1)Create a class inside your App_Data folder: (right-click app > Add > Add ASP.Net folder) (Add > New Item > Class)
important! when you add these classes, you have to switch the build action to "compile" instead of "content" in the properties of the file, otherwise your codebehind won't recognize the imported namespaces.
2)Inside the class, create methods:
namespace applicationName.App_Code
{
public class ClassName
{
public string classMethod()
{
return "hello";
}
}
}
3)On the codebehind of any form, include this class header:
using applicationName.App_Code; //add this
4)On the codebehind of this form, create an instance of the class:
ClassName classInstanceName = new ClassName(); //add this
5)Call the method in your form codebehind
classInstanceName.classMethod()
Upvotes: 1
Reputation: 3128
There are a lots of approaches you can take to sharing code between pages. It really depends on what type of functionality you are trying to achieve.
Here are some that I've encountered in the past:
Upvotes: 2
Reputation: 1924
Just create a .cs file is drop it in your App_Code directory. Make your class and appropriate functions public, and you're good to go.
Upvotes: 1
Reputation: 3402
You can create a library very easily in ASP.NET.
Decide on a namespace and create new classes under that namespace (generally each class in a separate file but it is not enforced)
If your ASPX files don't have code-behind I would recommend to add it, however regardless of whether there is a code-behind or not you would need to make sure you include the library files' namespace before you can access the library classes and their methods.
Syntax for including a namespace on a ASPX file is:
<%@ Import Namespace="mylibrarynamespace" %>
In the code-behind is:
using mylibrarynamespace;
Hope it helps.
Upvotes: 7
Reputation: 15237
How about making a base class from which all of your page classes derive? That seems like the simplest way to go.
Upvotes: 2