Separating Presentation from Code Using Code Behind

for RuBoard

Code in ASP.old was often difficult to maintain because it was interspersed with HTML markup. Even when using a visual development tool such as Visual InterDev or Dreamweaver UltraDev, it could be difficult and time consuming to track down a chunk of ASP code that needed to be debugged .

The solution to this problem is a tactic that developers on many platforms typically use: separating logic (the code that you write) from presentation (the way the data appears). By separating logic from presentation, you can be assured that all the code is located in the same place, organized the way you want, and easily accessible. Separating logic from presentation also minimizes the possibility that you'll generate new bugs in the presentation code as you debug the core logic of the application.

One tactic for separating code from presentation in ASP.NET is code behind. Code behind is a feature that enables you to take most of or all the code out of an ASP.NET page and place it in a separate file. The code is processed normally; the only difference is where the code is located.

Visual Basic actually introduced the concept of code behind. The idea was that the code that dealt with a particular object was in a different layer "behind" the object. Of course, this was only one way to describe it. In reality, code behind was just a separate source file for each form that encapsulated the code related to that form. The code in the file was actually tightly coupled with the form.

ASP.NET has this same concept with a slight twist. If you write a page as shown in Listing 2.7, behind the scenes ASP.NET parses the code out of the page for you ” invisibly in the background. A class is created that inherits from System.Web.Page and includes a class level object declaration for each runat =server control in your page. This is done by default to enable you to continue programming using the simple model provided in ASP.old.

Alternatively, you can create this class yourself and derive the page from it. This separates the code from the layout of the page. This separation is potentially a huge benefit. In my previous life I worked with a company whose standard development process went something like this: A business process owner would decide that some feature should be Web enabled. The owner would come to a designer with, at best, a couple of sketches of what the Web pages needed to implement this feature should look like. The owner would then work with the designer to create a series of HTML pages that represented the feature. These pages would then be handed off to a developer to "activate" them. The developer would go through the pages, adding the code to actually make the feature work. When the developer was done, the feature was then shown to the business process owner. Inevitably, the owner would realize that several features had been missed and/or additional features were needed So the process would start over again. The designer would take the completed pages and start moving the HTML around to meet the needs of the change requests . After the pages were again looking good, the designer would hand off to the developer. The developer would open up the pages and throw his or her hands up in despair. In the process of reformatting and rearranging the HTML, the designer inevitably would have scrambled the ASP.old code that had lived intermixed with the HTML. In many instances, it was easier for the developer to just rip the old code out and re-add it via copy/paste from the first version. This iterative process could continue for dozens of rounds, depending on the complexity of the feature.

I suspect my previous company and I were not the only ones frequently faced with this issue. It begs for a new model that allows the separation of the layout and formatting from the code that operates on it. ASP.NET is not Microsoft's first attempt at this concept. It was tried, as part of Web Classes in Visual Basic 6.0 but was not very successful. I predict that ASP.NET will be a much more successful implementation.

The way that code behind in ASP.NET works is that you create a class that inherits from System.Web.UI.Page. This is the base class for a page.

NOTE

A complete reference to the Page object can be found at the end of this chapter.


The .aspx page then inherits from the class you create. This inheritance is accomplished via the @Page directive that is discussed in further detail in this chapter. The @Page directive Inherits attribute enables you to indicate from which class the page should inherit.

The Src attribute enables you to indicate from which file the source code should be dynamically compiled. This last attribute is not required if the class has already been compiled and is in the Global Assembly Cache. Alternatively, under the directory the page is in, you can create a special directory called /bin. This directory is one of the first places ASP.NET looks for already compiled code. If the code has not already been compiled, the file reference by the Src attribute is compiled and looked at for the class specified in the Inherits attribute. Listing 2.8 shows the aspx page for the sample we have been looking at. Note that no code is in this page, just HTML markup.

Listing 2.8 SimplePage3.aspx Using Code Behind ”This is the .aspx Page
 <% @Page src="simplepage3.aspx.cs" Inherits="SimplePage" %> <html> <head>    <title>SimplePage3.aspx</title> </head> <body>     <form id="WebForm1" method="post" runat="server">       <p>       <table border=0>          <tr>             <td>Name:</td>             <td><asp:textbox id=txtName runat=server /></td>             <td><asp:button id=Button1 Text="Send" runat=server /></td>          </tr>          <tr>             <td valign=top>Hobby:</td>             <td>                <select id=lbHobbies Multiple runat=server>                   <option Value="Ski">Ski</option>                   <option Value="Bike">Bike</option>                   <option Value="Swim">Swim</option>                </select>             </td>             <td>&nbsp;</td>          </tr>       </table>       </p>       <asp:label id=lblOutput runat=server />     </form> </body> </html> 

Also note the @Page tag that indicates the code for this page is in a file called SimplePage3.aspx.cs. The class that implements the functionality for this page is called SimplePage. Listing 2.9 shows SimplePage3.aspx.cs.

Listing 2.9 Simplepage3.aspx.cs Is the Code Behind File for SimplePage3.aspx
 public class SimplePage : System.Web.UI.Page {    protected System.Web.UI.WebControls.Button Button1;    protected System.Web.UI.WebControls.TextBox txtName;    protected System.Web.UI.WebControls.Label lblOutput;    protected System.Web.UI.HtmlControls.HtmlSelect lbHobbies;    private void Page_Init()    {       Button1.Click += new System.EventHandler(Button1_Click);    }    private void Button1_Click(object sender, System.EventArgs e)    {       string strTemp;       // Build up the output       strTemp = "Name:" + txtName.Text + "<BR>Hobbies: ";       for(int iCount = 0; iCount <= lbHobbies.Items.Count - 1; iCount++)          if(lbHobbies.Items[iCount].Selected)             strTemp = strTemp + lbHobbies.Items[iCount].Text + ", ";       // Place it into the label that was waiting for it       lblOutput.Text = strTemp;    } } 

This looks very similar to the previous example, except that no code is in the page! It is strictly markup. One cool feature is that by altering the Inherits attribute, you can tie more than one aspx page to the same code-behind file. If you type the code in the previous two listings into Notepad and save using the recommended filenames, you will have a working page.

Code behind gives you an additional way to wire up events. It's best not to make the HTML markup know any more than it needs to about the code. Using the approach shown earlier to wire up events, you're required to know the name of the event procedure in the code behind. An alternative is to define the page event handlers in Page_Init(). In Listing 2.9 the Button1_Click function is defined as a handler for Button1.Click event. This is an alternative way to wire up the event handlers for ASP.NET with code behind. With this technique, the HTML markup doesn't have to know anything about the code-behind class.

for RuBoard


C# Developer[ap]s Guide to ASP. NET, XML, and ADO. NET
C# Developer[ap]s Guide to ASP. NET, XML, and ADO. NET
ISBN: 672321556
EAN: N/A
Year: 2005
Pages: 103

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net