Home » ASP.NET Basics » 07 - Writing code and handling events
7

The Code-behind model

Discussing the different models of writing code

We have seen so far that when we open a page in the VWD IDE, it has two views - design view and source view. In the design view, we design the page visually by using the toolbars, dragging, dropping the controls from the toolbox, resizing, and moving the controls by mouse. In the source view, we can do the same by writing equivalent HTML code. But where do we write the C# programming code?

The VWD IDE provides two methods for writing programming code. First is the inline model. In this model, we write the code in the source view. Let us see how to do this.

1. Start the VWD IDE. We are going to start a new project for this chapter. Let us call this project - CodeSample.

2. When VWD creates the project, it shows the Default.aspx page in source view. We will add a new page to our project. In the solution explorer, right click on the project name and select Add New Item... option from the menu.

3. In the Add New Item dialog box, select Web Form in the templates section, give a name to the page and make it sure that the two check boxes - Place code in separate file and Select master page - are unchecked. Click the Add button to continue.

4. The new page will open in the source view. It has the generated HTML code but notice the code near the top of the page:

 <script runat="server"> </script>

The section inside the <script runat="server"> and </script> tags is the place where we put our programming code when using the inline model. This section was automatically generated by the VWD IDE because we unchecked the box - Place code in separate file - when we added the page to our project. Un-checking that checkbox tells the IDE that we want to keep our code in the same file along with the HTML code.

Though we can write our code in the source view of the web page, it is recommended that we do not use this method if possible. The source view also contains the HTML code for our page and if we add the programming code to it, the entire page will become complex to maintain.

Another model is called the code-behind model. In this model, the programming code is stored in a separate file. The name of the file is the same as the name of the web page but it has a .aspx.cs extension. For example, if the web page is login.aspx, its code behind file will be login.aspx.cs.

For using the code-behind model, all we need to do is to check the box - Place code in separate file - while adding a web form to our project. This will create the code behind file for our web page.

We can view this file from the solution explorer. Double clicking our page or any control on it in design view will also open up the code behind file.