ASP.NET is Microsoft's server-side framework on .NET: compiled C# or VB.NET pages, an event-driven Web Forms model with server controls, validators, postback and ViewState, rich state management, and ADO.NET for databases. ASP.NET MVC and ASP.NET Core are its successors.
Medium 55 minSyllabus: “Server side scripting: ASP.NET”
Mark as
The idea in one minute
Classic web pages are like filling in a paper form and posting it: every submission starts from scratch. ASP.NET Web Forms tried to make the web feel like a desktop program — you drop a TextBox and a Button on a page and write a btnSave_Click method, as in Visual Basic. To keep up the illusion across stateless HTTP, every page carries a sealed envelope (ViewState) back and forth so it can remember what the controls looked like last time.
Key points — the night-before list
.NET: source → MSIL in an assembly → JIT-compiled to native code by the CLR, which adds garbage collection and type safety. CTS: shared types; CLS: interoperability rules.
Classic ASP (1996) = interpreted VBScript in .asp files; ASP.NET (2002) = compiled .NET languages, .aspx pages with code-behind, server controls and events.
A Web Form = .aspx markup + code-behind class (.aspx.cs) deriving from System.Web.UI.Page, tied by the @Page directive. Controls with runat="server" are programmable objects.
Validators: RequiredFieldValidator, CompareValidator, RangeValidator, RegularExpressionValidator, CustomValidator, ValidationSummary — run in the browser and again on the server (Page.IsValid).
Page events: PreInit → Init → InitComplete → PreLoad → Load → control events → LoadComplete → PreRender → PreRenderComplete → SaveStateComplete → Render → Unload. Use if (!IsPostBack) for first-load work.
ViewState = page state in the hidden field __VIEWSTATE (Base64, MAC-protected, not encrypted by default); works without cookies but enlarges pages.
State: client side — ViewState, ControlState, hidden fields, cookies, query strings; server side — Session, Application, Cache, Profile. Session modes: InProc (default), StateServer, SQLServer, Custom, Off; timeout 20 minutes.
ADO.NET: Connection, Command, DataReader (connected, forward-only, read-only) vs DataAdapter + DataSet/DataTable (disconnected). ExecuteReader, ExecuteScalar, ExecuteNonQuery; always use parameters.
01.NET foundations: CLR, CTS, CLS, MSIL and JIT
ASP.NET runs on Microsoft's .NET platform. The original .NET Framework 1.0 shipped in February 2002 with Visual Studio .NET and ran only on Windows (its last major version is 4.8). The cross-platform, open-source rewrite .NET Core arrived in 2016 and, from .NET 5 (2020), is simply called .NET (.NET 8 and .NET 10 are long-term-support releases).
From source code to running code
Compile to MSIL
The C#, VB.NET or F# compiler turns source code into MSIL (Microsoft Intermediate Language, standardised as CIL) plus metadata describing every type, stored in an assembly (.dll or .exe) with a manifest.
Load into the CLR
The Common Language Runtime loads the assembly, verifies the IL for type safety and checks security permissions.
JIT compilation
The Just-In-Time compiler converts each method's MSIL into native machine code the first time the method is called and caches it for the rest of the run.
Managed execution
The CLR runs the native code and provides garbage collection, exception handling, thread management and interop with unmanaged code.
Term
Meaning
CLR (Common Language Runtime)
The execution engine: JIT, garbage collector, type safety, exceptions, security, threads
CTS (Common Type System)
Defines all .NET types and how they behave — value types (int, struct) vs reference types (class, string) — so every language shares one type model
CLS (Common Language Specification)
A subset of CTS rules that a library follows so that any .NET language can use it (for example, no unsigned types in public members)
MSIL / CIL
CPU-independent instruction set produced by every .NET compiler
JIT compiler
Translates MSIL into native code at run time (ahead-of-time options such as NGen and ReadyToRun also exist)
Managed code
Code whose execution the CLR controls; unmanaged code (native C/C++, COM) runs outside it
FCL / BCL
Framework (Base) Class Library: collections, I/O, networking, ADO.NET, ASP.NET (System.Web)
Assembly
Unit of deployment and versioning (.dll/.exe) holding IL, metadata and a manifest; shared ones lived in the Global Assembly Cache (GAC)
PSC favourite
The JIT compiler converts MSIL into native machine code at run time; the language compiler converts source code into MSIL. Because every language compiles to the same IL and CTS, a class written in VB.NET can be inherited from in C#.
02Classic ASP vs ASP.NET
Active Server Pages (ASP), now called classic ASP, came with IIS 3.0 in 1996: .asp files mixed HTML with interpreted VBScript or JScript between <% %> markers, using built-in objects Request, Response, Session, Application and Server, and COM components such as ADO for data. ASP.NET, released with .NET in 2002, kept the idea of server pages but rebuilt everything on compiled, object-oriented .NET.
Aspect
Classic ASP
ASP.NET (Web Forms)
Languages
VBScript, JScript (interpreted)
C#, VB.NET and any .NET language (compiled)
Execution
Script interpreted on every request
Compiled to MSIL, JIT-compiled, cached
Page file
.asp
.aspx (plus .ascx user controls, .master pages)
Code organisation
Code mixed into HTML ('spaghetti code')
Code-behind class separated from markup
Programming model
Linear script writing HTML
Event-driven: server controls raise events such as Click
Page state
Developer keeps it manually
ViewState preserves control values automatically
Data access
ADO (COM)
ADO.NET (disconnected DataSet, DataReader)
Configuration
IIS metabase / registry
XML web.config files; edits take effect automatically, with no manual IIS restart
Interactive · Thread, applet, servlet/JSP & ASP.NET lifecycles Full page
Loading interactive tool…
03Web Forms: .aspx markup, code-behind and server controls
A Web Form is a pair of files. The .aspx file holds HTML plus server-control tags; the code-behind file (.aspx.cs for C#) holds a partial class that derives from System.Web.UI.Page and contains the event handlers. The @Page directive on the first line connects them. Input and postback controls (TextBox, Button, DropDownList…) must sit inside the page's single <form runat="server">.
HTMLLogin.aspx — CodeBehind names the code file (Web Application projects; Web Site projects use CodeFile) and Inherits names the class
C#Login.aspx.cs — the same users table as the PHP version; the hash is made by the platform's own helper (Crypto.HashPassword)
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Helpers; // Crypto.VerifyHashedPassword
using System.Web.UI;
namespace KshbPortal
{
public partial class Login : Page // code-behind: inherits System.Web.UI.Page
{
protected void btnLogin_Click(object sender, EventArgs e)
{
if (!Page.IsValid) return; // re-check the validators on the server
string cs = ConfigurationManager.ConnectionStrings["Kshb"].ConnectionString;
const string sql = "SELECT full_name, password_hash FROM users WHERE username = @u";
using (var con = new SqlConnection(cs))
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@u", txtUser.Text.Trim()); // parameter: no SQL injection
con.Open();
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (rd.Read() && Crypto.VerifyHashedPassword(rd.GetString(1), txtPass.Text))
{
Session["FullName"] = rd.GetString(0); // server-side session state
Response.Redirect("Welcome.aspx");
return;
}
}
}
lblError.Text = "Invalid username or password.";
}
}
}
HTML server controls
Ordinary HTML elements plus runat="server" and an id: <input id="txtName" runat="server" />
C#Welcome.aspx.cs — BoundField HTML-encodes its values by default, so the grid is safe from injected markup
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
namespace KshbPortal
{
public partial class Welcome : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["FullName"] == null) // not logged in
{
Response.Redirect("Login.aspx");
return;
}
lblName.Text = Server.HtmlEncode((string)Session["FullName"]); // Label does not encode
if (!IsPostBack) // bind data only on the first visit
{
string cs = ConfigurationManager.ConnectionStrings["Kshb"].ConnectionString;
using (var da = new SqlDataAdapter("SELECT name, district, units FROM schemes ORDER BY name", cs))
{
var table = new DataTable();
da.Fill(table); // opens and closes the connection itself
gvSchemes.DataSource = table;
gvSchemes.DataBind(); // the grid now keeps its rows in ViewState
}
}
}
protected void lnkLogout_Click(object sender, EventArgs e)
{
Session.Abandon(); // end the session
Response.Redirect("Login.aspx");
}
}
}
04Validation controls
Validation controls check user input without hand-written code. Each is attached to one input through ControlToValidate and shows ErrorMessage (collected by ValidationSummary) or Text (shown at the validator's own position). They run twice: in the browser through generated JavaScript (EnableClientScript), and on the server when the page is validated — so always test Page.IsValid in the event handler, because client-side checks can be bypassed.
Validator
Checks
Key properties
RequiredFieldValidator
The field is not empty (or not equal to an initial placeholder value)
InitialValue
CompareValidator
Compares with another control or a constant, or checks the data type
ControlToCompare / ValueToCompare, Operator (Equal, GreaterThan, DataTypeCheck…), Type
RangeValidator
The value lies between a minimum and a maximum
MinimumValue, MaximumValue, Type (Integer, Double, Date, String, Currency)
Lists all failed validators' messages in one place
HeaderText, DisplayMode, ShowMessageBox
HTML
<asp:TextBox ID="txtAge" runat="server"/><asp:RangeValidator runat="server" ControlToValidate="txtAge" Type="Integer"
MinimumValue="18" MaximumValue="60" ErrorMessage="Age must be 18 to 60" Text="*"/><asp:TextBox ID="txtPass" runat="server" TextMode="Password"/><asp:TextBox ID="txtConfirm" runat="server" TextMode="Password"/><asp:CompareValidator runat="server" ControlToValidate="txtConfirm" ControlToCompare="txtPass"
Operator="Equal" ErrorMessage="Passwords do not match" Text="*"/><asp:TextBox ID="txtEmail" runat="server"/><asp:RegularExpressionValidator runat="server" ControlToValidate="txtEmail"
ValidationExpression="^[^@\s]+@[^@\s]+\.[^@\s]+$" ErrorMessage="Invalid e-mail" Text="*"/><asp:TextBox ID="txtPin" runat="server"/><asp:CustomValidator runat="server" ControlToValidate="txtPin" OnServerValidate="ValidatePin"
ErrorMessage="Enter a Kerala PIN code (670000-695999)" Text="*"/><asp:ValidationSummary runat="server" HeaderText="Please correct the following:"/><asp:Button ID="btnRegister" runat="server" Text="Register" OnClick="btnRegister_Click"/>
C#
// in the code-behind (add using System.Linq; and using System.Web.UI.WebControls;)
protected void ValidatePin(object source, ServerValidateEventArgs args)
{
string pin = args.Value;
args.IsValid = pin.Length == 6 && pin.All(char.IsDigit)
&& int.Parse(pin) >= 670000 && int.Parse(pin) <= 695999;
}
protected void btnRegister_Click(object sender, EventArgs e)
{
if (!Page.IsValid) return; // stops here if any validator failed on the server// ... save the applicant ...
}
Watch out
An empty field passes every validator except RequiredFieldValidator (a CustomValidator checks empty text only when ValidateEmptyText="true"). To make an optional-looking field mandatory, pair it with a RequiredFieldValidator.
05Page life cycle, postback and IsPostBack
Every request — first visit or postback — creates a fresh Page object that runs through a fixed sequence of stages and is discarded afterwards. A postback is a POST of the page's form back to the same .aspx page, triggered by a Button or by a control with AutoPostBack="true" (which submits through the JavaScript function __doPostBack and the hidden fields __EVENTTARGET and __EVENTARGUMENT).
Event
What happens / typical use
PreInit
IsPostBack is known; set the master page or theme dynamically; create dynamic controls
Init
Each control is initialised; ViewState not yet loaded
InitComplete
ViewState tracking switches on
(postback only)
ViewState and control state are loaded; posted form values are applied to the controls
PreLoad
Fires after ViewState and post data have been loaded
Load
Page_Load: the most used event — read values, bind data inside if (!IsPostBack)
Control events
Change events first (TextChanged, SelectedIndexChanged, CheckedChanged), then the event that caused the postback (Button Click); validation runs before Click
LoadComplete
All loading and control events are done
PreRender
Last chance to change controls before HTML is generated
PreRenderComplete
Data-bound controls with a DataSourceID have bound
SaveStateComplete
ViewState has been saved; changes from now on are not persisted
Render
Not an event but a method: each control writes its HTML to the output stream
Unload
Clean-up — close files and connections; the response has already been sent
C#Without the !IsPostBack test, every postback would re-bind the list and wipe out the user's selection
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // first request only
{
ddlDistrict.DataSource = new[] { "Kollam", "Kochi", "Thrissur" };
ddlDistrict.DataBind(); // ViewState will remember the items
ddlDistrict.SelectedValue = "Kochi";
}
// on a postback the list and the user's new choice are restored automatically
}
Mnemonic
Please Initialise, Load, handle Events, then Pre-render, Save, Render, Unload — PreInit/Init, Load, control Events, PreRender, SaveStateComplete, Render, Unload.
Moving to another page: Response.Redirect("Welcome.aspx") sends a 302 so the browser makes a new request (the URL changes); Server.Transfer("Welcome.aspx") switches pages inside the server during the same request (the URL stays); a Button's PostBackUrl performs a cross-page postback, and the target reads the source through PreviousPage.
06ViewState and state management
ViewState stores the property values of the page and its controls in a hidden form field named __VIEWSTATE. When the page renders, the state is serialised, Base64-encoded and protected by a MAC (a keyed hash that detects tampering); on postback it comes back with the form and is restored before Page_Load. It is encoded, not encrypted by default — anyone can decode it — unless encryption is switched on. You can store your own values too: ViewState["Page"] = 2;.
ViewState advantages
No server memory — state lives in the page
Works with cookies disabled; needs no URL rewriting
Automatic for controls; simple ViewState["key"] API
Per page and per user, so no clashes
ViewState drawbacks
Enlarges every page download and every postback
Lasts only while the user stays on the same page
Readable by the user unless encrypted — never store secrets
Serialisation costs CPU; disable it with EnableViewState="false" where not needed
Profile.PreferredDistrict (properties declared in web.config)
C#Each snippet is independent — they would not normally run one after another
// cookie: persistent for 30 days, invisible to JavaScript
var c = new HttpCookie("district", "Kollam");
c.Expires = DateTime.Now.AddDays(30); // leave Expires unset for a session cookie
c.HttpOnly = true;
Response.Cookies.Add(c);
string d = Request.Cookies["district"]?.Value; // read on a later request// query string between pages (visible and editable — validate it!)
Response.Redirect("Scheme.aspx?id=" + 7);
int id = int.Parse(Request.QueryString["id"]);
// session: per user, on the server
Session["FullName"] = "Anil Kumar";
string who = (string)Session["FullName"]; // stored as object: cast back
Session.Remove("Cart"); // one item
Session.Timeout = 30; // minutes
Session.Abandon(); // end the whole session
Session mode (web.config)
Where the data lives
Notes
InProc (default)
Memory of the ASP.NET worker process (w3wp.exe)
Fastest; lost when the app pool recycles; unsuitable for web farms; the only mode that fires Session_End
StateServer
The ASP.NET State Service (aspnet_state.exe), port 42424 by default
Survives app restarts; can be shared by a web farm; objects must be serialisable
SQLServer
A SQL Server database (created with aspnet_regsql)
Most durable and farm-friendly; slowest
Custom
Your provider (e.g. Redis)
Plug in any store
Off
—
Session state disabled
The session id normally travels in the ASP.NET_SessionId cookie. With <sessionState cookieless="UseUri" /> it is embedded in every URL instead — for example /(S(lit3py55t21z5v55vlm25s55))/Welcome.aspx — which works without cookies but exposes the id in links, logs and Referer headers.
PSC favourite
Which ASP.NET feature preserves state across page requests without cookies or URL rewriting? → ViewState (asked in 2025). Session needs a cookie or a cookieless URL; QueryString is URL-based.
07web.config, Global.asax and master pages
Configuration lives in XML web.config files arranged in a hierarchy — machine.config, the framework's root web.config, the application's web.config, and optional web.config files in sub-folders, each overriding the one above. Editing web.config restarts the application automatically, and IIS never serves the file to browsers.
XMLRead settings with ConfigurationManager.ConnectionStrings["Kshb"] and ConfigurationManager.AppSettings["MaxUnitsPerApplicant"]
system.web also configures authentication (mode="Windows" for intranet sites using Windows accounts, "Forms" for a login page that issues an authentication cookie, "None") and authorization rules such as <deny users="?" /> (? = anonymous users, * = everyone).
ADO.NET is .NET's data-access library. A data provider supplies four core classes per database — SqlClient for SQL Server (System.Data.SqlClient, now Microsoft.Data.SqlClient), plus OleDb, Odbc and providers from Oracle and MySQL:
Object
Role
Connection (SqlConnection)
Opens a session with the database; pooled automatically by SqlClient
Command (SqlCommand)
An SQL statement or stored procedure with Parameters; executes it
DataReader (SqlDataReader)
Connected, forward-only, read-only stream of rows; fastest; holds the connection open while reading
DataAdapter (SqlDataAdapter)
Bridge for the disconnected model: Fill() loads a DataSet/DataTable, Update() writes changes back
DataSet / DataTable
Provider-independent in-memory copy of tables, relations and constraints; can be serialised to XML
C#
string cs = ConfigurationManager.ConnectionStrings["Kshb"].ConnectionString;
// 1. Connected: DataReader
using (var con = new SqlConnection(cs))
using (var cmd = new SqlCommand("SELECT name, units FROM schemes WHERE district = @d", con))
{
cmd.Parameters.AddWithValue("@d", ddlDistrict.SelectedValue); // parameterised
con.Open();
using (SqlDataReader rd = cmd.ExecuteReader())
{
while (rd.Read()) // one row at a time, forward only
{
lstSchemes.Items.Add(rd["name"] + " (" + rd.GetInt32(1) + " units)");
}
}
} // Dispose() closes: back to the pool// 2. Single value and data changes
using (var con = new SqlConnection(cs))
{
con.Open();
int total = (int)new SqlCommand("SELECT COUNT(*) FROM schemes", con).ExecuteScalar();
var upd = new SqlCommand("UPDATE schemes SET units = units - 1 WHERE id = @id AND units > 0", con);
upd.Parameters.AddWithValue("@id", 7);
int changed = upd.ExecuteNonQuery(); // rows affected: 1, or 0 if none left
}
// 3. Disconnected: DataAdapter + DataSet
var ds = new DataSet();
using (var da = new SqlDataAdapter("SELECT id, name, district, units FROM schemes", cs))
{
var builder = new SqlCommandBuilder(da); // generates INSERT/UPDATE/DELETE
da.Fill(ds, "Schemes"); // opens, reads all rows, closes
DataTable t = ds.Tables["Schemes"];
t.Rows[0]["units"] = 130; // edit offline, in memory
da.Update(ds, "Schemes"); // reconnects and saves the changes
}
Connected (DataReader)
Connection stays open while you read
Forward-only, read-only, one row in memory
Fastest, lowest memory — ideal for display
ExecuteReader()
Disconnected (DataAdapter + DataSet)
Connection opened only during Fill() and Update()
Random access, editable, many tables and relations
More memory; good for offline editing, caching, XML
Fill() and Update()
ExecuteReader() — rows (SELECT). ExecuteScalar() — the first column of the first row (COUNT, MAX, a new id). ExecuteNonQuery() — rows affected by INSERT, UPDATE or DELETE (−1 for other statements).
Always use parameters (@name) instead of string concatenation, and using blocks so connections return to the pool even after an exception.
ASP.NET MVC (2009) replaced pages-with-events by Model–View–Controller: controllers handle routes such as /Schemes/Details/7, Razor views (.cshtml, since 2011) render HTML, there is no ViewState or postback, and testing is easier. Web API (2012) builds REST services.
ASP.NET Core (2016) is the cross-platform, open-source rewrite: the Kestrel web server, a middleware pipeline, built-in dependency injection, MVC, Razor Pages, Blazor, minimal APIs and SignalR. It does not include Web Forms; Microsoft suggests Blazor for migrating Web Forms applications.
Step through · First request and postback of Login.aspx
step 1 / 10
Step 1: GET /Login.aspx
The first visit: an ordinary GET. IIS hands .aspx requests to the ASP.NET runtime in the worker process.
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Tracing the page life cycle on a first visit and a postback
A page has a TextBox txtName (AutoPostBack off) with a TextChanged handler, a Button btnSave with a Click handler, and handlers for PreInit, Init, Load, PreRender and Unload that log their names. List the events for (a) the first request and (b) a postback after the user changes the text and clicks Save.
EX 2Choosing a state-management technique
Pick the best technique for each: (a) the current page number of a GridView while the user stays on that page; (b) the logged-in officer's name, needed on every page; (c) the number of users online, shared by everybody; (d) the user's preferred language for the next 6 months; (e) the id of the scheme to show on Scheme.aspx when clicking a link; (f) a list of districts read from the database, identical for all users and refreshed every 10 minutes.
EX 3Which ADO.NET method, and what does it return?
For each task choose ExecuteReader, ExecuteScalar, ExecuteNonQuery or DataAdapter.Fill and give the result: (a) count the schemes in Kollam; (b) reduce units by 1 for scheme 7 when 5 units remain; (c) the same update when 0 units remain (the WHERE clause includes units > 0); (d) show all schemes in a GridView that supports sorting without re-querying; (e) stream 50,000 rows into a CSV file.
EX 4Designing validation for a registration form
Fields: name (mandatory), age (18 to 60), password and confirm password (must match), e-mail (valid format), PIN code (must be a Kerala PIN, 670000–695999). Which validators would you attach, and why is Page.IsValid still needed?
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
A DropDownList is filled in Page_Load without an IsPostBack test. Users complain that after clicking Save their selected district always resets to the first item. Explain the cause and fix it.
Q2
A GridView shows 500 rows × 4 columns with about 20 characters per cell, all kept in ViewState. Estimate the ViewState size after Base64 encoding and the extra data transferred per postback.
Q3
Write the web.config element that stores sessions in SQL Server with a 30-minute timeout, and give one advantage and one cost compared with InProc. What happens to Session_End?
Q4
Write Global.asax code that counts page requests for the whole site, and explain why Application.Lock() is needed.
Q5
Name the 6 validation controls and say which one you would use to check (a) that a 'Joining date' is a valid date, (b) that 'Units requested' is not more than 'Units available' shown in another TextBox, (c) a rule that needs a database lookup.
Exam traps
The code-behind class derives from System.Web.UI.Page — not System.Web.UI.Form or System.Windows.Forms.Form.
IsPostBack is false on the first request and true on postbacks; data binding normally belongs inside if (!IsPostBack).
ViewState is Base64-encoded and MAC-protected, not encrypted by default — do not store passwords or prices you trust in it.
Session_End fires only with InProc session state, never with StateServer or SQLServer.
Render is a method, not an event; PreRender is the last event where control changes still count.
Every validator except RequiredFieldValidator treats an empty field as valid.
Quiz — KPSC style
10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
ASP.NET Web Forms, ADO.NET & state · Question 1 of 10✓ 0 · ✗ 0
An ASP.NET Web Form's code-behind class inherits by default from:
Past-paper questions on this topic
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
Past papers · Question 1 of 2✓ 0 · ✗ 0
Modelled on QP 050/2026 · Deputy Manager (IT) / Assistant Programmer / Computer Programmer etc (20 May 2026), Q.65 (reworded)original paper (PDF)
By default, an ASP.NET Web Forms page class derives from which base class?