Slide 11.3: Adding simple code to a page
Slide 11.5: Adding simple code to a page (cont.)
Home

Adding Simple Code to a Page (Cont.)

Without Using Code Render Blocks
The ID values of the Label, TextBox, and DropDownList are “Result,” “Name,” and “Category,” respectively. The command
   Result.Text = "Hi " + Name.Text + ", you selected: "
      + Category.SelectedValue;
puts the string with the Text property of TextBox Name1 and the SelectedValue property of DropDownList Category to the Text property of Label Result. The SelectedValue property of a DropDownList gets the value of the selected item in the list control.

Using Code Render Blocks
ASP.NET page developers can utilize <% %> code blocks to dynamically modify HTML output much as they can today with ASP. For example, the following sample demonstrates how <% %> code blocks can be used to interpret results posted back from a client.

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

using System;
namespace WebApplication3 {
  public partial class WebForm1 : System.Web.UI.Page {
    protected void Page_Load( object sender, EventArgs e ) {
    }
    protected void Lookup_Click( object sender, EventArgs e ) {
      Result.Text = "Hi " + Name.Text + ", you selected: "
          + Category.SelectedValue;
    }
  }
}

intro3.aspx (using code render blocks)

<%@ Page Language="C#" AutoEventWireup="true" 
   CodeBehind="intro3.aspx.cs" Inherits="WebApplication3.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 action="intro3.aspx" method="get">
   <h3> Name: <input name="Name" type="text" value="
     <% =HttpUtility.HtmlEncode(Request.QueryString["Name"])%>" />
    Category:
    <select name="Category" size="1">
     <%
      int i;
      String[] values = new String[3];
      values[0] = "psychology";
      values[1] = "business";
      values[2] = "popular_comp";
     %>
     <% for (i = 0; i < values.Length; i++) {
      if ( HttpUtility.HtmlEncode(Request.QueryString["Category"])
          == values[i] ) { 
     %>
       <option selected="selected">
        <% =values[i] %>
       </option>
      <% } else { %>
       <option> 
        <% =values[i] %>
       </option>
      <% } } %>
   </select>
   <input type="submit" name="Lookup" value="Lookup">
   <p>
    <% if ( Request.QueryString["Lookup"] != null ) %>
     Hi <% =HttpUtility.HtmlEncode(Request.QueryString["Name"]) %>,
     you selected:
     <% =HttpUtility.HtmlEncode(Request.QueryString["Category"]) %>
   </p>
   </h3>
  </form>
 </center></body>
</html>

Web