Home   Cover Cover Cover Cover

aspx Page With Code-behind

From Section 6.1 of the book

Script code can also be implemented in a code-behind file. This has the advantage that the aspx page is kept free of script code. The following example shows a page counter where the method CounterValue() has been implemented in the following code-behind file.

using System.IO;

public class CounterPage : System.Web.UI.Page {
  public int CounterValue() {
    FileStream s = new FileStream(Server.MapPath("Counter.dat"), FileMode.OpenOrCreate);
    int n = 0;
    try {
      BinaryReader r = new BinaryReader(s);
      n = r.ReadInt32();
    } catch {}
    s.Seek(0, SeekOrigin.Begin);
    BinaryWriter w = new BinaryWriter(s);
    return n;

The aspx page that uses this method looks as follows:

<%@ Page Language="C#" Inherits="CounterPage" Src="Simple3.aspx.cs" %>
    <title>Page Counter</title>
    You are visitor number <%= CounterValue() %> to this page!

Try it