Use extension methods on your ASPX page

  1. Create a Webapplication project
  2. Edit the Default.aspx to look like this:
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %> 
    <%@ Import Namespace="Berend.PageExtensions" %> 
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    
    <html xmlns=http://www.w3.org/1999/xhtml> 
      <head runat="server"> 
        <title></title> 
      </head> 
      <body> 
       <form id="form1" runat="server"> 
          <div> 
            <h1> 
              <%=this.MyPageExtensionMethod()%> 
            </h1> 
          </div> 
        </form> 
      </body> 
    </html>
    
  3. Remember to add the namespace (which contains your extension method) to your aspx
  4. Add a class library to your project and code the following class:
    namespace Berend.PageExtensions 
    { 
        public static class Class1 
        { 
            public static string MyPageExtensionMethod(this Page p) 
            { 
                return "Extension method executed!"; 
            } 
        } 
    } 
    
  5. This class Class1 contains the extension method (remember to make the class and the method static)
  6. Press F5 and your extension method gets executed.

When you want to use this technique with SharePoint 2007 you have to follow the steps in this post to run WSS under the .NET 3.5 framework!

Share

Leave a Reply

Your email address will not be published. Required fields are marked *