1. Introduction to ASP.NET
What is ASP.NET?
ASP.NET is a Microsoft web development framework used
to build dynamic, data-driven and interactive web
applications using the .NET ecosystem.
Developers can use C# with ASP.NET to implement business
logic, interact with databases, process user requests,
validate data and create complete web applications.
ASP.NET is not a programming language.
ASP.NET is a web application development framework.
C# is a programming language commonly used to build
ASP.NET applications.
Major ASP.NET Technologies
| Technology |
Purpose |
| Web Forms |
Event-driven web application development
using .aspx pages and server controls.
|
| MVC |
Structured web development using
Model, View and Controller.
|
| Web API |
Building HTTP-based REST APIs for applications
and client applications.
|
ASP.NET Application Architecture
A typical database-driven ASP.NET application contains
several logical layers.
Client
→ Browser
Presentation Layer
→ ASP.NET Web Forms / MVC
Business Layer
→ C# application logic
Data Access Layer
→ ADO.NET / Entity Framework
Database
→ SQL Server
Separating responsibilities makes applications easier
to understand, maintain, test and extend.
ASP.NET MVC
MVC stands for Model-View-Controller. It separates
application data, user interface and request-processing
logic into different components.
Model → Data and business representation
View → User interface
Controller → Handles requests and
coordinates application operations
ASP.NET Web API
Web API is used to create HTTP-based services that can
be consumed by web applications, mobile applications,
desktop applications and other systems.
APIs commonly exchange data using JSON.
Example JSON
{
"studentId": 101,
"name": "Rahul Kumar",
"course": "C# Programming"
}
2. ASP.NET Web Forms Fundamentals
Creating a Web Forms Project
An ASP.NET Web Forms application typically contains
pages with the .aspx extension and corresponding
code-behind files.
Example project structure
Site.master
Default.aspx
Default.aspx.cs
Courses.aspx
Courses.aspx.cs
Web.config
ASP.NET Page Life Cycle
A Web Forms page passes through a sequence of stages
during a request.
- Page Request
- Start
- Initialization
- Load ViewState
- Load PostBack Data
- Load
- PostBack Event Handling
- Rendering
- Unload
Page_Load Example
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Code executed only during
// the first page load.
}
}
Code-Behind
Code-behind allows server-side C# logic to be separated
from the HTML and ASP.NET markup.
Default.aspx
<asp:Button
ID="btnMessage"
runat="server"
Text="Click Me"
OnClick="btnMessage_Click" />
<asp:Label
ID="lblMessage"
runat="server" />
Default.aspx.cs
protected void btnMessage_Click(
object sender,
EventArgs e)
{
lblMessage.Text = "Welcome to ASP.NET!";
}
Server Controls
ASP.NET server controls are processed on the server
and provide properties, events and server-side
functionality.
| Control |
Purpose |
| Label |
Displays text |
| TextBox |
Accepts user input |
| Button |
Triggers server-side action |
| DropDownList |
Allows selection from a list |
| CheckBox |
Represents a true/false selection |
| GridView |
Displays tabular data |
PostBack and IsPostBack
A postback occurs when a page sends a request back to
the server, commonly as a result of a server control
event.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadCourses();
}
}
Why IsPostBack matters:
It prevents initialization code such as database
binding from running unnecessarily during every
postback.
Validation Controls
ASP.NET validation controls provide a convenient way
to validate user input before processing a form.
RequiredFieldValidator
<asp:TextBox
ID="txtName"
runat="server" />
<asp:RequiredFieldValidator
ID="rfvName"
runat="server"
ControlToValidate="txtName"
ErrorMessage="Name is required."
CssClass="text-danger" />
Important Validation Controls
- RequiredFieldValidator
- RangeValidator
- CompareValidator
- RegularExpressionValidator
- CustomValidator
- ValidationSummary
Master Pages
Master Pages allow common elements such as navigation,
headers, footers and site layouts to be shared across
multiple Web Forms pages.
Site.Master
<asp:ContentPlaceHolder
ID="MainContent"
runat="server">
</asp:ContentPlaceHolder>
Individual content pages then provide their content
through the corresponding Content control.
State Management
HTTP is stateless. ASP.NET provides different mechanisms
for preserving information between requests.
| Technique |
Scope |
| ViewState |
Current page |
| ControlState |
Server control state |
| Session |
Individual user |
| Application |
Entire application |
| Cookies |
Client browser |
| QueryString |
URL parameters |
Session Example
Session["UserName"] = "Rahul";
string name = Session["UserName"].ToString();
3. Database Programming with ADO.NET
What is ADO.NET?
ADO.NET is a .NET data access technology used to
communicate with relational databases.
In an ASP.NET application, ADO.NET can be used to
execute SQL commands, retrieve records, insert data,
update records and delete data.
Application
↓
ADO.NET
↓
SQL Server
Database Connection
SqlConnection represents a connection to a SQL Server
database.
C#
using System.Data.SqlClient;
string connectionString =
@"Data Source=.;Initial Catalog=StudentDB;
Integrated Security=True";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
connection.Open();
// Database operations
}
In production applications, connection strings should
normally be stored securely in configuration rather
than hard-coded into source files.
SqlCommand
SqlCommand is used to execute SQL statements or
stored procedures against SQL Server.
string query =
"SELECT StudentName FROM Students";
using (SqlCommand command =
new SqlCommand(query, connection))
{
// Execute command
}
Parameterized SQL should be used when values come from
users. Avoid building SQL statements by concatenating
raw user input.
SqlDataReader
SqlDataReader provides a fast, forward-only way to
read rows returned from a database query.
string query =
"SELECT StudentID, StudentName FROM Students";
using (SqlCommand command =
new SqlCommand(query, connection))
using (SqlDataReader reader =
command.ExecuteReader())
{
while (reader.Read())
{
string name =
reader["StudentName"].ToString();
}
}
SqlDataAdapter, DataSet and DataTable
A DataAdapter can populate disconnected data structures
such as DataSet and DataTable.
string query =
"SELECT * FROM Students";
using (SqlDataAdapter adapter =
new SqlDataAdapter(query, connection))
{
DataTable table = new DataTable();
adapter.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
}
4. DataSource Controls
What are DataSource Controls?
DataSource controls provide a declarative way to connect
ASP.NET data-bound controls to data sources.
They can reduce the amount of repetitive data access
code required for common database operations.
Common DataSource Controls
- SqlDataSource
- ObjectDataSource
- AccessDataSource
- SiteMapDataSource
SqlDataSource
SqlDataSource allows an ASP.NET page to connect to
SQL Server and execute configured commands.
ASPX
<asp:SqlDataSource
ID="dsStudents"
runat="server"
ConnectionString="<%$ ConnectionStrings:StudentDB %>"
SelectCommand="SELECT * FROM Students">
</asp:SqlDataSource>
A connection string can be defined in Web.config using
the ConnectionStrings section and referenced from the
ASP.NET page.
GridView
GridView is one of the most commonly used ASP.NET
Web Forms data-bound controls. It displays records
in a tabular format and can support operations such
as selection, editing, deleting, paging and sorting.
Basic GridView
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="true">
</asp:GridView>
Bind Data
GridView1.DataSource = table;
GridView1.DataBind();
GridView CRUD Operations
GridView can be used with data sources to create
database-driven interfaces for viewing and managing
records.
Display Data
protected void Page_Load(
object sender,
EventArgs e)
{
if (!IsPostBack)
{
LoadStudents();
}
}
private void LoadStudents()
{
// Retrieve records from database
// and bind them to GridView.
}
Delete Example
protected void GridView1_RowDeleting(
object sender,
GridViewDeleteEventArgs e)
{
int studentId =
Convert.ToInt32(
GridView1.DataKeys[e.RowIndex].Value);
// Execute parameterized DELETE query.
}
Always validate and authorize database operations.
A delete button in the user interface should not be
treated as sufficient protection for destructive
operations.
GridView Paging and Sorting
Paging prevents large numbers of records from being
displayed on a single page.
Enable Paging
<asp:GridView
ID="GridView1"
runat="server"
AllowPaging="true"
PageSize="10"
AllowSorting="true">
</asp:GridView>
For very large datasets, efficient server-side paging
is preferable to loading every record into memory.
5. ASP.NET MVC
MVC Architecture
MVC separates an application into three primary
components.
Model
Represents application data and domain logic.
View
Presents information to the user.
Controller
Receives requests and coordinates application logic.
Typical Request Flow
Browser
→ Controller
→ Model / Database
→ Controller
→ View
→ Browser
Model
A model represents data used by the application.
Student.cs
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
View
A View is responsible for presenting information to
the user.
Razor View Example
@model Student
<h2>Student Details</h2>
<p>
Name: @Model.StudentName
</p>
<p>
City: @Model.City
</p>
The MVC example above uses Razor syntax and is separate
from the Web Forms .aspx syntax used in the earlier
sections.
Controller
Controllers receive requests, execute appropriate
application logic and return a response.
StudentController
public class StudentController
: Controller
{
public ActionResult Index()
{
return View();
}
}
Routing
Routing maps an incoming URL to an appropriate
controller action.
Example URL
/Student/Details/10
This could map to a Details action of StudentController
with an ID value of 10.
Model Validation
MVC applications can use data annotation attributes
to define validation rules on models.
public class Student
{
public int StudentID { get; set; }
[Required]
public string StudentName { get; set; }
[Range(18, 60)]
public int Age { get; set; }
}
Validation should be enforced on the server even when
client-side validation is also enabled.
6. ASP.NET Web API
What is a REST API?
A REST-style API exposes resources through HTTP
endpoints and uses standard HTTP methods to perform
operations.
| Method |
Typical Purpose |
| GET |
Retrieve data |
| POST |
Create a resource |
| PUT |
Update a resource |
| DELETE |
Delete a resource |
HTTP Methods
Web APIs use HTTP requests to communicate with clients.
Each HTTP method communicates the intended type of
operation.
GET → Read
POST → Create
PUT → Update
DELETE → Remove
GET Request
A GET endpoint returns information to the client.
Example
[HttpGet]
public IEnumerable<Student> GetStudents()
{
return students;
}
Example Endpoint
GET /api/students
POST Request
POST is generally used to create a new resource.
[HttpPost]
public IHttpActionResult CreateStudent(
Student student)
{
// Save student.
return Ok(student);
}
PUT and DELETE
PUT
[HttpPut]
public IHttpActionResult UpdateStudent(
int id,
Student student)
{
// Update student.
return Ok();
}
DELETE
[HttpDelete]
public IHttpActionResult DeleteStudent(
int id)
{
// Delete student.
return Ok();
}
JSON in Web API
JSON is commonly used to represent structured data
exchanged between APIs and clients.
{
"studentID": 101,
"studentName": "Rahul Kumar",
"age": 21,
"city": "Delhi"
}
A frontend application can send JSON to an API and
receive JSON in response.
7. Practical Project — Student Management System
Project Objective
Build a database-driven Student Management System that
demonstrates the major technologies covered in this
course.
Core Features
- Add new students.
- Display students in GridView.
- Edit student records.
- Delete student records.
- Search students.
- Validate form input.
- Store records in SQL Server.
- Use Master Page for common layout.
- Implement database access using ADO.NET.
- Expose student information through an API.
Suggested Database
CREATE TABLE Students
(
StudentID INT PRIMARY KEY IDENTITY(1,1),
StudentName VARCHAR(100) NOT NULL,
Email VARCHAR(150) UNIQUE,
Age INT CHECK (Age >= 18),
City VARCHAR(50),
Course VARCHAR(100),
IsActive BIT DEFAULT 1
);
Final Application Architecture
The completed project can be organized into multiple
layers and interfaces.
Web Forms Application
Student Registration
Student List
GridView CRUD
↓
Business Logic
Validation
Application Rules
↓
Data Access
ADO.NET
SqlConnection
SqlCommand
SqlDataReader
↓
SQL Server
Students Table
Extension — MVC Version
The same Student Management System can then be
recreated using MVC to understand how the same
business requirement can be implemented using a
different architectural pattern.
Extension — Web API Version
Finally, expose student records through REST endpoints
so that another application can retrieve, create,
update and delete student information through HTTP.
Final Learning Outcome
After completing this course, a learner should be able
to understand the fundamentals of ASP.NET Web Forms,
develop server-side applications using C#, connect
applications to SQL Server, display and manage data
using GridView, implement validation and state
management, understand MVC architecture, and build
basic REST-style Web APIs.
Practice Challenges
Beginner
- Create a Web Forms registration form.
- Add TextBox, DropDownList and CheckBox controls.
- Add validation controls.
- Create a Master Page.
- Create three content pages.
Intermediate
- Create a Student database.
- Connect ASP.NET to SQL Server.
- Display records using GridView.
- Implement insert, update and delete.
- Add search, sorting and paging.
Advanced
- Build the Student Management System.
- Create an MVC version of the application.
- Create REST API endpoints.
- Return student information as JSON.
- Connect a client application to the API.
Course Summary
ASP.NET provides a complete ecosystem for building
database-driven web applications. In this course,
you explored both the fundamentals and practical
application-development concepts.
- ASP.NET fundamentals
- Web Forms and code-behind
- Page life cycle and postback
- Server controls
- Validation controls
- Master Pages
- State management
- ADO.NET
- SqlConnection and SqlCommand
- SqlDataReader and DataAdapter
- DataSource controls
- GridView
- GridView CRUD
- Paging and sorting
- MVC architecture
- Models, Views and Controllers
- MVC routing and validation
- REST APIs
- HTTP methods
- JSON
- Student Management System
Recommended Learning Approach:
Do not only read the examples. Create the project,
type the code yourself, connect it to SQL Server,
introduce small changes, intentionally test invalid
input, and build the final Student Management System
from the individual concepts.