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.

Simple3.aspx.cs
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 {}
    n++;
    s.Seek(0, SeekOrigin.Begin);
    BinaryWriter w = new BinaryWriter(s);
    w.Write(n);
    s.Close();
    return n;
  }
}

The aspx page that uses this method looks as follows:

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

Try it

   http://dotnet.jku.at/book/samples/6/Simple3.aspx