views:

216

answers:

3

I have a huge code behind file for one of my ASP.NET pages. It would be easier to maintain the code if I could break it up into multiple partial classes. However this is not well documented for ASP.NET.

I've learned that the additional partial classes must be moved into the App_Code folder. It seems that I need to use Protected WithEvents declarations to reference my web controls (although I'm not sure that will work yet).

My hang up right now is the ViewState. I cannot reference that in the additional partial class file. I need to get an ID number from the query string in the partial class. If I create a public property in the code behind file for the query string value, it cannot be referenced in the partial class file. It does not show up.

+2  A: 

Sounds like you need to create some classes to encapsulate some of your logic. You can always import the Web specific assemblies into your custom classes should you need to effect changes to the controls on your page.

David Robbins
A: 

If your code-behind file is really that big, then you probably need to push some of the logic out into other classes. Learn the Model-View-Controller pattern and investigate the ASP.NET MVC framework to see how to better lay out your objects.

It's a big code smell in ASP.NET to drop everything into code-behind files. It leads to non-scalable and unmaintainable applications.

Jeffrey Cameron
A: 

Thinking in layers is a good approach. Think about how you interact with the database and what objects you're retrieving data for, and create "Data layer" classes for them. Their purpose should strictly be to interact with the database and return maybe a dataset with the appropriate data (create a standard and follow it!). Then think about what business rules you're enforcing on the data for that object and create a "Business layer" class with methods that invoke your data layer class and apply those rules in this layer. At this point, the data should be ready to display, and your "Presentation layer" (code-behind) is responsible for where/when/how that is performed.

My explanation isn't that good, but hopefully you get the idea.

erick.brower