Team LiB
Previous Section Next Section

Code-Beside/Code Separation

Code-behind was a very useful and comfortable feature for web developers. But I have some bad news: Code-behind is dead. Hey, don't worry—you'll use the new code-beside model instead.

Code-behind was smart, but from an object-based view it was far from perfect. The designed ASPX page was derived from a class that was generated in parts by the development environment. You had to declare controls in both files, and manual changes often resulted in problems. There are a lot of good reasons to move away from code-behind.

The solution is code-beside, which is supposed to make everything better, brighter, and of course more object oriented. This is what the ASP.NET team promises. Instead of using the class derivation as it was up to now, the design file and the source code file are created as partial classes that will be merged by the compiler (I describe partial classes in Chapter 1). This approach means that there's no automatically generated source code at all. Both files work hand in hand, and you can assign events directly in the server control tags.

To add a new code-beside page, right-click the project in Solution Explorer and choose Add New Item. Then select Web Form Using Code Separation in the following dialog box and click Open. Now the project contains two new files, one with the design and one with the source code. The two files are nothing new, but the source code file doesn't include any directives generated by the IDE. VS .NET has just built an empty partial class.

Figure 2-17 shows an example of code-beside. The page contains a Label control and a Button control. Clicking the Button control will assign new text to the Label control.

Click To expand
Figure 2-17: Code-beside keeps your files clean.

The old code-behind model isn't supported in the current Alpha version, but it will be supported in the Beta version. So don't worry about migrating your projects.

Tip 

You can use code-beside pages and single file pages within one project without any problems.VS .NET handles the files in an appropriate manner automatically, and it takes care that you get the right information while debugging. Currently, code-beside is available for pages as well as for user controls and web services.

Tip 

Put source code in the code-beside file and in the ASPX file, and then try to debug the page. What happens? Yeah, the compiler always jumps into the correct file—well done!


Team LiB
Previous Section Next Section