I have a .aspx Web Form with a .aspx.cs code-behind. The code-behind is nearly 2000 lines long, and it's getting to the point where the only way to easily navigate it is to put a ton of spaces in between the sections, zoom out so I can see the physical look of the code, and then zoom in where I want to edit. In other words, it's a major pain. I'd like to split this 2000 line into different files that represent concepts in the code. So when I need to go edit some functionality in the "Employee" jquery tab of the page, I can just go to the partial class that contains just the "Employee" functionality.
In the New Item menu, I cannot find anything for an additional code-behind file, no .aspx.cs file. I tried creating a .cs file, renaming it to .aspx.cs, and giving it the same partial class name --- no go, I couldn't see any of the methods of the default partial class, nor the controls on the page.
I understand the concept that if your "class", in the OOP sense, is that long, it's doing too much. What I don't understand is a "class" in terms of code-behind for a web form. The form can't really be broken down into smaller forms --- the user experience needs to all take place on one page.
Partial classes help split the methods into two or more source(. cs) files. All the partial classes will be combined when the whole program is compiled. Partial Class is a unique feature of C#. It can break the functionality of a single class into many files.
The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace. All the parts must use the partial keyword. All the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public , private , and so on.
A partial class allows a single class to be divided into two separate physical files. During compile time these files get compiled into a single class. For instance, you can see in the following figure we have the customer class divided into two different files "customer1. cs" and "customer2.
You could use partial classes. So add a new .cs
file to your project and use a partial class.
For example assuming you currently have the following Default.aspx.cs
file:
public partial class _Default : System.Web.UI.Page
{
... some 2000 lines of code
}
you could add another .cs file to your project in which:
public partial class _Default
{
... a subset of the 2000 lines of code could be moved here
in order to isolate some functionality
}
It's very important that this partial class is declared in exactly the same namespace as the original class and has the same name.
But note that using partial classes only hides the shit. It doesn't clean it. If you want to clean it you will have to consider OOP practices to split functionality in different classes. You should layer your application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With