ASP.NET Web Forms

FDN » .NET Framework » ASP.NET Web Forms

ASP.NET Web Forms

ASP.NET Web Forms is a page-based framework for building web applications with server-side controls and event-driven programming: similar to building Windows Forms applications.

Page Structure

An ASP.NET page has two files: the .aspx markup file and the .aspx.cs (or .aspx.vb) code-behind file.

<!-- Default.aspx -->
<%@ Page Language="C#" CodeBehind="Default.aspx.cs" Inherits="FlamenetWeb.Default" %>
<html>
<body>
  <form runat="server">
    <h1>Flamenet Web Portal</h1>
    <asp:TextBox ID="txtName" runat="server" />
    <asp:Button ID="btnGreet" runat="server" Text="Greet"
                OnClick="btnGreet_Click" />
    <asp:Label ID="lblMessage" runat="server" />
  </form>
</body>
</html>
// Default.aspx.cs
using System;

namespace FlamenetWeb
{
    public class Default : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.TextBox txtName;
        protected System.Web.UI.WebControls.Label lblMessage;

        protected void btnGreet_Click(object sender, EventArgs e)
        {
            lblMessage.Text = "Hello, " + Server.HtmlEncode(txtName.Text) + "!";
        }
    }
}

Page Lifecycle

EventDescription
PreInitSet master page, theme. Create dynamic controls.
InitControls initialized. ViewState not loaded yet.
LoadViewState and form data loaded. Page_Load fires here.
Control EventsButton clicks, dropdown changes, etc.
PreRenderLast chance to modify controls before rendering.
RenderHTML generated and sent to the client.
UnloadCleanup. Cannot modify the response.

ViewState

ViewState is a mechanism that preserves control values across postbacks. It is stored as a hidden __VIEWSTATE field in the HTML form. While convenient, ViewState can increase page size significantly. Disable it for controls that do not need to preserve state:

<asp:DataGrid ID="dgResults" runat="server" EnableViewState="false" />

Key Differences from Classic ASP

  • Compiled code (not interpreted): much faster
  • Strong typing and IntelliSense support
  • Server controls with event model (no manual HTML generation)
  • Code-behind separation of markup and logic
  • Built-in session state options: InProc, StateServer, SQL Server
« Developer Network ‹ C# Language Primer ADO.NET Data Access ›