O'Reilly logo

Programming ASP.NET, 3rd Edition by Dan Hurwitz, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Code-Behind

You can interweave content, such as HTML, text, server controls, and program code in a single file, as was done with traditional ASP. This is known, cleverly, as the single-file model.

To see an example of the single-file model, look at CodeSingleFile.aspx, listed in Example 6-1. If you place this file in a folder on your machine, (such as c:\websites), create a virtual directory pointing to that folder, named, for example, Websites, and then enter the following URL in your browser:

http://localhost/websites/CodeSingleFile.aspx

Example 6-1. CodeSingleFile.aspx

<%@ Page Language="C#" %>
 

<script runat="server">
    protected void btnHello_Click(object sender, EventArgs e)
    {
       lblMessage.Text = "Hello. The time is " +
            DateTime.Now.ToLongTimeString();
    }
</script>
 
<html>
<head runat="server">
    <title>Code-Beside</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <h1>Code-Beside</h1>
       <asp:Button ID="btnHello" runat="server"
                   Text="Hello"
                   OnClick="btnHello_Click" />
       <br />
       <asp:Label ID="lblMessage" runat="server"  />
    </div>
    </form>
</body>
</html>

The page will appear, containing a button that will display a text string every time it is clicked.

Tip

Unlike previous versions of Visual Studio, Intellisense now works in content files in VS2005. This is true in code blocks as well as with the HTML and server controls.

The single file still requires a Page directive, and any compiled server-code is contained within <script> tags (highlighted in Example 6-1). For this web page, the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required