views:

454

answers:

5

Hi,

When you create a new asp.net page in VS 2008 and choose code behind, it also creates the typical aspx.vb or aspx.cs file to go along with it.

At the top of those files, VS names the 'Partial Class' name the file structure and/or name of the aspx file.

The question: Is there a best practice for this? Can I just use a single class name for all the pages in my application or perhaps a single directory instead of having to give each one a unique name?

Chris

A: 

No, each page must be a different class (assuming they are actually doing different things). This is because you're really creating a subclass of Page for each of your pages, and then overriding the default logic with your specific behaviors. So each set of behaviors (each "Page type") is a different class.

BRH
+1  A: 

The code-behind is specific for the individual page. Messing with it will break the aspx model (see the "inherits" or similar at the top of the aspx page).

Each aspx page (in regular ASP.NET) should have a separate class.

In ASP.NET MVC, note that a single controller class is commonly associated with multiple related views (and that the aspx/ascx don't tend to have code-behind in MVC).

Marc Gravell
A: 

It's actually somewhat common to use the same class as the "code-behind" for many ASPX pages. If you find yourself doing a lot of 1-to-1 between base page classes and their associated ASPX files, it makes sense to stick with the default model. But if that doesn't make sense for your application, there's nothing preventing you from pointing all your ASPX Inherits properties to the same class.

Of course, as with anything, it's always best to learn the rules before breaking them. The normal WebForms model does fit most use cases, especially for developers who are beginning or intermediate to the ASP.NET WebForms platform. So make sure you know enough to know what you're getting into before you start changing stuff :)

Rex M
+1  A: 

In our project, since most of the actual work is done by server controls inserted to page by server side tags, we don't actually need codebehind in most of the pages. Hence, around 18 of our 22 aspx pages don't even have the <%Page%> directive on them. Default page base class is set from web.config file:

 <pages masterPageFile="~/MasterPage.master" pageBaseType="OurProject.OurBasePageClass">
 </pages>
Gorkem Pacaci
+3  A: 

I think the reason for the "partial class" is to allow Visual Studio to put all the declarations in a separate file, so that they don't clutter up the code-behind. In addition to the aspx.vb/cs file, there's also a designer.vb/cs file, which contains all the control declarations.

Take a look at http://stackoverflow.com/questions/480915/asp-net-partial-classes-and-inheritance for a bit more information.

chris