Code Blocks in ASP.NET

The ASP.NET single-file page model is similar to Active Server Pages (ASP) page structure in that script blocks that contain code come before HTML, and special markup tags can be used in the HTML. This topic describes the issues involved in updating your ASP code to ASP.NET.

The ASP.NET code-behind page model separates script-block code from the HTML and ASP.NET markup tags. For more information, see ASP.NET Web Page Syntax Overview. For information about data-binding syntax that enables you to bind control property values to data, see Data-Binding Expressions Overview.

Declaring Variables and Procedures

All ASP.NET procedures and global variables should be declared within <script runat="server"> blocks placed before the opening <html> tag, not between ASP <%...%> style delimiters. You can still declare variables in <%...%> render blocks, but they will be accessible only to other render blocks on the page, not globally to other functions or procedures. A page can contain more than one script block, but the programming language must be the same in all blocks on a page.

The following code example is for an ASP.NET page that declares variables and procedures in a script and render block. If you pass a query string to the ASP.NET page in the URL, the query string is displayed on the page.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    ' The following variables are visible to all procedures 
    ' within the <script> block.
    Dim str As String
    Dim i, i2 As Integer

    Function DoubleIt(ByVal inpt As Integer) As Integer
        ' The following variable is visible only within 
        ' the DoubleIt procedure.
        Dim factor As Integer = 2

        DoubleIt = inpt * factor
    End Function
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <% 
        ' The following local variable is visible only within this
        ' and other render blocks on the page.
        Dim myVar

        myVar = Request.QueryString
        Response.Write("The querystring is " _
           & Server.HtmlEncode(myVar.ToString()))
    %>
    </div>
    </form>
</body>
</html>
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    // The following variables are visible to all procedures 
    // within the <script> block.
    String str;
    int i;
    int i2;

    int DoubleIt(int inpt)
    {
        // The following variable is visible only within 
        // the DoubleIt procedure.
        int factor = 2;

        return inpt * factor;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <% 
      // The following local variable is visible only within this
      // and other render blocks on the page.
      object myVar;

      myVar = Request.QueryString;
      Response.Write("The querystring is " + 
         Server.HtmlEncode(myVar.ToString()));
    %>
    </div>
    </form>
</body>
</html>

Rendering Text

Render functions are not supported in ASP.NET. Using older versions of ASP, you could insert literal HTML within a procedure body, as shown in the following code example.

   <% Sub SomeProcedure() %>
   <H3> Render this line of bold text. </H3>
   <% End Sub %>

This code would generate an error in an ASP.NET page. For ASP.NET, you would have to write the code as follows.

   <script runat=server>
      Sub SomeProcedure()
         Response.Write("<H3> Render this line in bold text.</H3>")
      End Sub
   </script>

All code that is included within the <script>…</script> tags, except global variable declarations, must be encapsulated within procedures.

Page Processing, Loading and Unloading

With ASP, code was enclosed within <%...%> tags and page processing began with the first statement following the first <%> tag. With ASP.NET, any code that is to be processed as soon as the page is loaded must be included within the Page_Load intrinsic event. You can still write code in <%...%> blocks, but it will be executed at render time (in top-down fashion, as in ASP) after the page is loaded. If you need to execute initialization code, it should appear in the Page_Load event, which is raised immediately after the page is loaded by the ASP.NET engine, as shown in the following code example.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        ' Place all startup code here, including initialization of 
        ' variables,  preloading of controls, and loading of 
        ' data from a database.
        If Page.IsPostBack Then
            Response.Write("<br />Page has been posted back.")
        End If

    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Hello.<br />
    <asp:Button ID="Button1" runat="server" 
    Text="Click to Post Back" />
    </div>
    </form>
</body>
</html>
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            Response.Write("<br />Page has been posted back.");
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Hello.<br />
    <asp:Button ID="Button1" runat="server" 
    Text="Click to Post Back" />
    </div>
    </form>
</body>
</html>

A related Page_Unload intrinsic event is always the last event to be raised during the page execution life cycle and can be used to execute any page cleanup code.

For more information, see ASP.NET Page Life Cycle Overview and ASP.NET Web Server Control Event Model.

See Also

Concepts

ASP.NET Page Class Overview

ASP.NET Web Page Code Model

Client Script in ASP.NET Web Pages

ASP.NET Web Page Syntax Overview

ASP.NET Page Life Cycle Overview

ASP.NET Web Server Control Event Model

Other Resources

Migrating to ASP.NET