Dot Net TechnologyUnit 817 min read
ASP.NET Web Programming: MVC, AJAX, IIS, Razor Pages & WebForms
Unit 8 of Dot Net Technology covers ASP.NET architecture, WebForms vs. MVC vs. Razor Pages, AJAX controls, IIS virtual directories, session management, and real-world web application development with C. Learn to build dynamic, scalable web apps using server-side controls, database integration, and client-side interacti
ASP.NET Architecture: The Backbone of Web Applications
ASP.NET is a server-side web application framework developed by Microsoft for building dynamic websites, web services, and APIs. It runs on the .NET Framework and integrates seamlessly with C#, Visual Studio, and SQL Server.
Key Components of ASP.NET
classDiagram
class RequestProcessing {
+Client sends HTTP request
+ASP.NET handles request via IIS
+Middleware processes request
+Controller/Page handles logic
+Response sent back to client
}
class IIS {
+Internet Information Services
+Hosts ASP.NET applications
+Manages virtual directories
+Supports HTTPS, URL rewriting
}
class ASPNETCore {
+Cross-platform (Windows/Linux/Mac)
+Modular middleware pipeline
+Dependency injection built-in
+High performance (Kestrel server)
}
class WebForms {
+Event-driven model (like WinForms)
+ViewState for state management
+Server controls (GridView, DropDownList)
}
class MVC {
+Model-View-Controller pattern
+Separation of concerns
+Razor syntax for views
}
class RazorPages {
+Page-based model (simpler than MVC)
+Hybrid of MVC and WebForms
+Direct code-behind files
}
IIS --> RequestProcessing : Hosts
ASPNETCore --> RequestProcessing : Core
WebForms --> RequestProcessing : Legacy
MVC --> RequestProcessing : Modern
RazorPages --> RequestProcessing : SimplifiedHow ASP.NET Processes a Request
- Client sends an HTTP request (e.g.,
GET /Home/Index). - IIS (Internet Information Services) routes the request to the ASP.NET application.
- Middleware (e.g., authentication, error handling) processes the request.
- Controller/Page executes logic (C# code) and interacts with the Model (database).
- View (Razor/ASPX) renders the response.
- Response is sent back to the client.
ASP.NET vs. ASP.NET Core: Key Differences
| Feature | ASP.NET (Framework) | ASP.NET Core |
|---|---|---|
| Platform | Windows-only | Cross-platform (Windows/Linux/Mac) |
| Performance | Moderate (IIS-dependent) | High (Kestrel server, optimized) |
| Dependency Injection | Manual setup (Unity/Ninject) | Built-in (Microsoft.Extensions.DependencyInjection) |
| Modularity | Monolithic (all-in-one) | Modular (add/remove middleware) |
| HTTP Request Pipeline | Fixed (ASP.NET pipeline) | Customizable (middleware pipeline) |
| Database Access | ADO.NET, Entity Framework (older versions) | EF Core (lightweight, cross-platform) |
| Deployment | IIS required | Self-hosted or IIS |
| Example Use Case | Legacy enterprise apps (Windows-only) | Cloud-native apps (Azure, Docker) |
Real-World Example:
- Nepal’s eSewa uses ASP.NET Core for its backend APIs to handle high traffic during festival seasons (e.g., Dashain, Tihar). The cross-platform nature allows it to scale on Linux servers in data centers.
- Khalti’s payment gateway likely uses ASP.NET Core for its RESTful APIs, ensuring fast response times for transactions.
WebForms vs. MVC vs. Razor Pages: Which to Choose?
1. WebForms (Legacy Approach)
- Event-driven model (like Windows Forms).
- ViewState maintains state between requests (can bloat page size).
- Server controls (e.g.,
<asp:GridView>) simplify UI development. - Best for: Quick prototyping, simple CRUD apps, legacy migration.
Example: User Registration Form (WebForms)
// Code-behind (Default.aspx.cs)
protected void btnRegister_Click(object sender, EventArgs e)
{
string name = txtName.Text;
string email = txtEmail.Text;
// Save to database
SqlConnection con = new SqlConnection("connectionString");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Users VALUES (@name, @email)", con);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@email", email);
cmd.ExecuteNonQuery();
con.Close();
lblMessage.Text = "Registration successful!";
}
<!-- Default.aspx (Markup) -->
<asp:TextBox ID="txtName" runat="server" />
<asp:TextBox ID="txtEmail" runat="server" />
<asp:Button ID="btnRegister" runat="server" Text="Register" OnClick="btnRegister_Click" />
<asp:Label ID="lblMessage" runat="server" />
State After Clicking "Register":
sequenceDiagram
Client->>IIS: POST /Default.aspx
IIS->>ASP.NET: Route to Default.aspx
ASP.NET->>btnRegister_Click: Execute C# code
btnRegister_Click->>SQL Server: INSERT INTO Users
SQL Server-->>btnRegister_Click: Success
btnRegister_Click->>lblMessage: Set Text="Success"
ASP.NET-->>Client: Render updated page2. MVC (Model-View-Controller)
- Separation of concerns: Model (data), View (UI), Controller (logic).
- No ViewState: Lighter, more control over HTML.
- Razor syntax for dynamic views (
@Model.Property). - Best for: Complex apps, APIs, SPAs (Single Page Apps).
Example: Employee Registration (MVC)
// Controller (EmployeeController.cs)
public class EmployeeController : Controller
{
public IActionResult Register()
{
return View();
}
[HttpPost]
public IActionResult Register(Employee model)
{
if (ModelState.IsValid)
{
// Save to database
_dbContext.Employees.Add(model);
_dbContext.SaveChanges();
return RedirectToAction("Success");
}
return View(model);
}
}
<!-- View (Register.cshtml) -->
@model Employee
<h2>Employee Registration</h2>
<form asp-action="Register" method="post">
<input asp-for="Name" />
<input asp-for="Email" />
<button type="submit">Submit</button>
</form>
State After Submitting Form:
stateDiagram-v2
[*] --> Client: Loads Register.cshtml
Client --> Controller: POST /Employee/Register
Controller --> Model: Validates Employee
Model --> Database: INSERT INTO Employees
Database --> Controller: Success
Controller --> View: Redirect to Success
View --> Client: Render Success page3. Razor Pages (Simplified MVC)
- Page-based model (no controllers for simple apps).
- Direct code-behind (like WebForms but with MVC features).
- Less boilerplate than MVC.
- Best for: Small to medium apps, CRUD operations.
Example: Session Management (Razor Pages)
// Code-behind (Index.cshtml.cs)
public class IndexModel : PageModel
{
public void OnGet()
{
HttpContext.Session.SetString("UserName", "JohnDoe");
}
public void OnPost()
{
string userName = HttpContext.Session.GetString("UserName");
// Use session data
}
}
<!-- Index.cshtml -->
@page
<h2>Session Demo</h2>
<form method="post">
<button type="submit">Get Session Data</button>
</form>
<p>User: @HttpContext.Session.GetString("UserName")</p>
State After Setting Session:
AJAX in ASP.NET: Making Web Apps Responsive
AJAX (Asynchronous JavaScript and XML) allows partial page updates without full postbacks.
ASP.NET AJAX Controls
| Control | Purpose |
|---|---|
ScriptManager |
Enables AJAX on the page. |
UpdatePanel |
Defines a region that updates asynchronously. |
UpdateProgress |
Shows loading indicators during AJAX calls. |
Timer |
Triggers periodic updates (e.g., stock prices). |
AsyncFileUpload |
Uploads files without postback. |
Example: Live Search with AJAX (WebForms)
// Default.aspx.cs
protected void txtSearch_TextChanged(object sender, EventArgs e)
{
string query = txtSearch.Text;
// Call a web service or database
string results = GetSearchResults(query);
lblResults.Text = results;
}
<!-- Default.aspx -->
<asp:TextBox ID="txtSearch" runat="server" AutoPostBack="true" OnTextChanged="txtSearch_TextChanged" />
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Label ID="lblResults" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
State After Typing "Dot" in Search Box:
Real-World Example:
- Daraz’s search bar uses AJAX to fetch product suggestions as you type, improving user experience without full page reloads.
- Pathao’s ride tracker updates the driver’s location in real-time using AJAX polling (or WebSockets in modern versions).
IIS and Virtual Directories: Hosting ASP.NET Apps
What is IIS?
Internet Information Services (IIS) is Microsoft’s web server for hosting ASP.NET applications. It:
- Processes HTTP requests.
- Manages virtual directories (logical paths to physical folders).
- Supports HTTPS, URL rewriting, and application pools.
Creating a Virtual Directory in IIS
- Open IIS Manager.
- Right-click Sites → Add Virtual Directory.
- Enter:
- Alias:
MyApp(URL path, e.g.,http://localhost/MyApp). - Physical Path:
C:\MyApp\.
- Alias:
- Set permissions for the IIS_IUSRS user.
Example: Hosting a Razor Pages App
Real-World Example:
- Nepal’s NTC website (
ntc.gov.np) is hosted on IIS (or a similar server) to manage traffic updates and user logins. - Ncell’s billing portal uses virtual directories to separate different services (e.g.,
/billing,/support).
Session Management in ASP.NET
Sessions allow you to store user-specific data across requests.
How Sessions Work
- Session ID is stored in a cookie.
- Server-side session state is maintained (default: in-memory or SQL Server).
- Data is serialized and stored until the session expires.
Example: Shopping Cart Session (Razor Pages)
// Index.cshtml.cs
public void OnGet()
{
if (HttpContext.Session.GetString("Cart") == null)
{
HttpContext.Session.SetString("Cart", "[]");
}
}
public void OnPostAddToCart(string product)
{
string cart = HttpContext.Session.GetString("Cart");
// Deserialize, add product, serialize back
var cartItems = JsonSerializer.Deserialize<List<string>>(cart);
cartItems.Add(product);
HttpContext.Session.SetString("Cart", JsonSerializer.Serialize(cartItems));
}
State After Adding "Laptop" to Cart:
Real-World Example:
- Khalti’s checkout page uses sessions to maintain the cart items and user details until payment is completed.
- eSewa’s login session persists until the user logs out or the session expires (typically 30 minutes).
Exam Tip: How to Score Full Marks
- Compare ASP.NET vs. ASP.NET Core in a table (as above). Examiners love structured comparisons.
- Draw state diagrams for:
- MVC request flow.
- AJAX UpdatePanel updates.
- Session management.
- Code snippets must include:
- Razor syntax (
@model,@foreach). - AJAX controls (
<asp:ScriptManager>,<asp:UpdatePanel>). - Session management (
HttpContext.Session).
- Razor syntax (
- Real-world ties:
- Relate MVC to Nepal Stock Exchange (NEPSE) trading platform.
- Link AJAX to Pathao’s live tracking.
- Connect IIS to NTC’s website hosting.
- Common pitfalls to avoid:
- Forgetting
runat="server"in WebForms. - Not disposing
SqlConnection(useusingblocks). - Mixing Razor syntax (
@) with HTML (<% %>).
- Forgetting
- For short-answer questions:
- Define AJAX: "Asynchronous JavaScript and XML for partial page updates without full postbacks."
- Virtual Directory: "A logical path in IIS mapping to a physical folder for hosting web apps."
- MVC: "Model-View-Controller pattern separating data, UI, and logic for maintainable apps."
Worked Example: Employee Registration System (ASP.NET Core MVC)
Requirements:
- Create a form to register employees (ID, Name, Department).
- Save data to SQL Server.
- Display all employees on a separate page.
Step 1: Model (Employee.cs)
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}
Step 2: Controller (EmployeeController.cs)
public class EmployeeController : Controller
{
private readonly AppDbContext _db;
public EmployeeController(AppDbContext db)
{
_db = db;
}
// GET: /Employee/Register
public IActionResult Register()
{
return View();
}
// POST: /Employee/Register
[HttpPost]
public IActionResult Register(Employee emp)
{
if (ModelState.IsValid)
{
_db.Employees.Add(emp);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(emp);
}
// GET: /Employee/Index
public IActionResult Index()
{
var employees = _db.Employees.ToList();
return View(employees);
}
}
Step 3: Views
Register.cshtml
@model Employee
<h2>Employee Registration</h2>
<form asp-action="Register" method="post">
<div>
<label>ID:</label>
<input asp-for="Id" />
</div>
<div>
<label>Name:</label>
<input asp-for="Name" />
</div>
<div>
<label>Department:</label>
<input asp-for="Department" />
</div>
<button type="submit">Submit</button>
</form>
Index.cshtml
<h2>Employee List</h2>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Department</th>
</tr>
@foreach (var emp in Model)
{
<tr>
<td>@emp.Id</td>
<td>@emp.Name</td>
<td>@emp.Department</td>
</tr>
}
</table>
Step 4: Database Context (AppDbContext.cs)
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<Employee> Employees { get; set; }
}
Step 5: Program.cs (Setup)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Employee}/{action=Register}");
app.Run();
Trace: Registering Employee "John, IT"
| Step | Action | State After Step |
|---|---|---|
| 1 | User loads /Employee/Register |
View renders empty form. |
| 2 | User enters ID=1, Name=John, Department=IT |
Model binds to Employee object. |
| 3 | User clicks Submit | Register(Employee) POST method called. |
| 4 | Model validation passes | _db.Employees.Add(emp) executes. |
| 5 | SaveChanges() |
Database inserts Id=1, Name=John, Department=IT. |
| 6 | Redirect to /Employee/Index |
View renders table with John, IT. |
Real-World Tie: This mimics Nepal’s NTC employee management system, where new employees are registered in a database and displayed in a list for HR.
Summary Checklist for Exams
- Can you compare ASP.NET vs. ASP.NET Core in a table?
- Can you draw the MVC request flow as a sequence diagram?
- Can you write a Razor Page with session management?
- Can you explain AJAX UpdatePanel with a state diagram?
- Can you host a virtual directory in IIS and explain its purpose?
- Can you tie one example to a real Nepalese app (e.g., Khalti, eSewa, NTC)?
Based on the TU BCA syllabus for Dot Net Technology (CACS408), unit 8.
Discussion
Loading…