Slide 11.2: Writing your first ASP.NET page
Slide 11.4: Adding simple code to a page (cont.)
Home

Adding Simple Code to a Page

Without Using Code Render Blocks
This approach puts code in the .aspx.cs file or in the element <script language="C#" runat="server"> of the .aspx file. The ID value of the empty Label is “Result.” The command
   Result.Text += "<font size='" + i.ToString( ) +
      "'>Welcome to ASP.NET</font>";
will put the string “Welcome to ASP.NET” of various sizes to the Text property of the Label. VB includes various type conversion functions, each of which coerces an expression to a specific data type. For example, the function ToString converts a numeric value to String.

Using Code Render Blocks
ASP.NET provides syntax compatibility with existing ASP pages. This includes support for <% %> code render blocks that can be intermixed with HTML content within an .aspx file. These code blocks execute in a top-down manner at page render time. The below example demonstrates how <% %> render blocks can be used to loop over an HTML block (increasing the font size each time): Unlike with ASP, the code used within the above <% %> blocks is actually compiled—not interpreted using a script engine. This results in improved runtime execution performance.

intro2.aspx.cs (without using code render blocks)

using System;
namespace WebApplication1 {
  public partial class WebForm1 : System.Web.UI.Page {
    protected void Page_Load( object sender, EventArgs e ) {
    }
    protected void Lookup_Click( object sender, EventArgs e ) {
      for ( int i = 0; i < 8; i++ )
        Result.Text += "<font size='" + i.ToString( ) + 
          "'>Welcome to ASP.NET</font>";
    }
  }
}

intro2.aspx (using code render blocks)

<%@ Page Language="C#" AutoEventWireup="true" 
   CodeBehind="intro1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
 <body><center>
  <form ID="form1" runat="server">
   <h3>Name: <asp:TextBox ID="Name" runat="server">
    Category:
    <asp:DropDownList ID="Category" runat="server">
     <asp:ListItem Selected="True">psychology</asp:ListItem>
     <asp:ListItem>business</asp:ListItem>
     <asp:ListItem>popular_comp</asp:ListItem>
    </asp:DropDownList>
    <asp:Button ID="Lookup" Text="Lookup"
        OnClick="Lookup_Click" runat="server" />
    <p>
     <% for ( int i = 0; i < 8; i++ ) { %>
     <font size="<% =i %>">Welcome to ASP.NET</font>
     <% } %>
    </p>
   </h3>
  </form>
 </center></body>
</html>

Web