Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse same functions in different .aspx files or make function library?

Tags:

c#

asp.net

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.

like image 395
afaf12 Avatar asked May 22 '11 23:05

afaf12


4 Answers

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.

like image 57
Giuseppe Romagnuolo Avatar answered Nov 08 '22 22:11

Giuseppe Romagnuolo


How about making a base class from which all of your page classes derive? That seems like the simplest way to go.

like image 27
Tim Avatar answered Nov 08 '22 22:11

Tim


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:

  1. Using a base page - you can make your aspx pages derive from a custom class that dervies from Page. This way, you can call base.MethodName(). This is especially useful if you would need access to private/protected members/events.
  2. Put methods in a class - you can create a custom class that houses your methods. I suggest doing this if all the methods are related and it makes sense to bundle them in one class. Your requirements will also dictate whether the class should be static/instantiated (to me, its more like choosing between System.IO.File vs System.IO.FileInfo). Downside to this, is you cant access any private members of the page or fire any of its events.
  3. Extension methods - its kind of like #2, except its static and tied closely to the Page type. The syntax makes it more readable (in my opinion). However, there are certain design guidelines that you should consider.
like image 2
Mel Avatar answered Nov 08 '22 23:11

Mel


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.

like image 1
Justin C Avatar answered Nov 08 '22 21:11

Justin C