In my last post, I described how to add code blocks to your custom SharePoint 2007 pages. In this post, I will describe a similar technique that allows you to use the ASP.NET 2.0 code-behind model for your pages. Apparently, this was easier to achieve in SharePoint 2003, and I have seen quite a few posts out there from frustrated people who haven't been able to get this working in SharePoint 2007.
First, I created a minimal test page in Visual Studio 2005. Here's the contents of Test.aspx:
<%@ Page Language="C#" CodeFile="Test.aspx.cs" Inherits="SPCodeBehind.Test" %>
SharePoint 2007 Code-Behind Test Page
And here's the contents of Test.aspx.cs:
using System;
using System.Web.UI;
namespace SPCodeBehind
{
public partial class Test : Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Button1.Text = DateTime.Now.ToString();
}
}
}
It's just a simple page with a button that changes its label when clicked. It looks like this:
Next, I used the Publish Web Site feature in Visual Studio 2005 to prepare my code for deployment to my SharePoint site. First, I generated a strong-name key pair file:
C:\Program Files\Microsoft Visual Studio 8\VC>sn -k "C:\Users\WillA\Desktop\SPCodeBehind.snk"
Then, I published the code to a folder on my local machine (using my key file):
Next, I created a new test.aspx page in my SharePoint site using SharePoint Designer, and then pasted the contents of my published page into the new page:
Next, I ran the page in my SharePoint site. I knew it would fail since I hadn't told SharePoint where my code-behind DLL was yet. Here's the error message:
An error occurred during the processing of /Test.aspx. Could not load the assembly 'App_Web_7kov8md2'. Make sure that it is compiled before accessing the page.
Next, I copied the DLL into the bin folder of my SharePoint site and retried the page. Again, an error!
The base type 'SPCodeBehind.Test' is not allowed for this page. The type is not registered as safe.
Next, I modified the web.config file of my SharePoint site to include the following line:
Another error, but this one looks familiar – it's the same error I got when I tried to add a code block to my page in my last blog post!
An error occurred during the processing of /Test.aspx. The event handler 'OnClick' is not allowed in this page.
Finally, I modified the web.config file one last time:
Success! J
Please note that I used namespaces, strong-named assemblies, and checked the AllowPartiallyTrustedCallerAttribute option when publishing my initial code. I'm not 100% positive yet if all of these are required to get this working, but it's what I ended up with after much trial and error. Please let me know if you have additional information, or find a better way to do any of this. Good luck!