Maybe this is obvious to everyone but me because I've found no discussions on the topic...or maybe my googling skills just stink...or maybe both...but after looking at the markup in some of SharePoint's ASPX pages and seeing neither a CodeBehind nor a CodeFile attribute in the
Page Directive, it occurred to me that at least precompiled ASPX pages don't need either of these attributes. The required attribute is Inherits. Presumably, the .NET runtime uses the fully qualified assembly name in the Inherits attribute to discover the code behind for the requested page.
Here's what I mean...
When I start a new
Web Application Project in Visual Studio 2008 (or add a new page to such a project) and look at the markup in the ASPX page, I see a page directive declaration like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Examples.CodeBehindAttrTest.Default" %>
I can jump to the code-behind file (Default.aspx.cs) and add this code to the Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(String.Format("The time is: {0}", System.DateTime.Now.ToString()));
}
I can compile and run my project, browse to the default.aspx page, and see the timestamp print out with no problem.
So, what happens when I remove the CodeBehind attribute? Well, the very same behavior happens. This makes sense, too, because I don't deploy CS files to my production Web servers yet I make great use of code-behind files. Of course, Microsoft basically says as much:
"This attribute [CodeBehind] is not used at run time." (from the
Page Directive reference)
For your
Web Site projects, I assume you could equally remove the CodeFile attribute, but that appears much stickier, what with having to
precompile the site, setting the Inherits attribute correctly, and all.
The drawback of removing the CodeBehind attribute from your pages seems to be one of development-time convenience. Without knowing what code file represents a given ASPX page, should I, say, try to add a click event handler to my server side button by double-clicking the button in the Design tab, Visual Studio will add server-side code inline to my ASPX page instead of the default behavior of taking me to my code-behind page. If I cut and paste the inline code, drop it into my code behind page, recompile, and run the app, the event will fire as coded in my compiled DLL. Visual Studio is even smart enough to declare my button control in the designer partial class.