Session 6.5 – Introduction to ASP.NET

Module 6: Advanced Web Technologies | Duration: 1 hr

Learning Objectives

By the end of this session, students will be able to:

  • Understand the ASP.NET framework and its architecture
  • Compare ASP.NET with PHP and other web technologies
  • Understand the MVC (Model-View-Controller) pattern
  • Work with Razor syntax for dynamic web pages
  • Create basic ASP.NET web applications
  • Understand the .NET ecosystem and tooling

Introduction to ASP.NET

ASP.NET is a free, cross-platform, open-source framework for building modern web applications and services with .NET. It's maintained by Microsoft and the .NET community.

What is ASP.NET?
  • Framework: Built on the .NET platform
  • Language: Primarily C#, also supports VB.NET and F#
  • Platform: Cross-platform (Windows, macOS, Linux)
  • Architecture: Supports MVC, Web API, Blazor, and more
  • Performance: Known for excellent performance and scalability
ASP.NET Core MVC

Modern MVC framework for web applications and APIs

ASP.NET Web API

RESTful API framework for HTTP services

Blazor

Build interactive web UIs using C# instead of JavaScript

ASP.NET Framework Overview

.NET Architecture
Application Layer
ASP.NET Core MVC | Web API | Blazor | Razor Pages
Framework Layer
.NET Core Runtime | ASP.NET Core Libraries
Base Class Library
Collections | I/O | Networking | Security | Threading
Key Features
High Performance

ASP.NET Core is one of the fastest web frameworks, with excellent request throughput and low latency.

Cross-Platform

Develop and deploy on Windows, macOS, and Linux. Host in IIS, Apache, Docker, or self-host.

Modular Design

Include only the packages you need via NuGet. Reduces application footprint and improves security.

Dependency Injection

Built-in dependency injection support promotes loose coupling and testability.

MVC Pattern in ASP.NET

MVC Architecture
Model
  • Data structures
  • Business logic
  • Database operations
  • Data validation
View
  • User interface
  • Presentation logic
  • Razor templates
  • Display data
Controller
  • Handles requests
  • Processes input
  • Updates models
  • Selects views
Controller Example
using Microsoft.AspNetCore.Mvc; using MyApp.Models; namespace MyApp.Controllers { public class HomeController : Controller { // GET: /Home/Index public IActionResult Index() { return View(); } // GET: /Home/About public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } // GET: /Home/User/5 public IActionResult User(int id) { var user = GetUserById(id); if (user == null) { return NotFound(); } return View(user); } // POST: /Home/Create [HttpPost] public IActionResult Create(User user) { if (ModelState.IsValid) { // Save to database SaveUser(user); return RedirectToAction("Index"); } return View(user); } } }
Model Example
using System.ComponentModel.DataAnnotations; namespace MyApp.Models { public class User { public int Id { get; set; } [Required(ErrorMessage = "Name is required")] [StringLength(100)] public string Name { get; set; } [Required] [EmailAddress] public string Email { get; set; } [Range(18, 120)] public int Age { get; set; } [DataType(DataType.Password)] public string Password { get; set; } [Display(Name = "Registration Date")] public DateTime RegisteredAt { get; set; } } }

Razor Syntax

Razor is a markup syntax for embedding server-based code into web pages. It uses the @ symbol to transition from HTML to C#.

Basic Razor Syntax
@* This is a Razor comment *@ <!-- Display variable --> <p>Hello, @Model.Name!</p> <!-- Code block --> @{ var message = "Welcome to ASP.NET"; var currentYear = DateTime.Now.Year; } <h1>@message</h1> <p>Copyright © @currentYear</p> <!-- Conditional rendering --> @if (Model.IsLoggedIn) { <p>Welcome back, @Model.Username!</p> } else { <p><a href="/login">Please log in</a></p> } <!-- Loop --> <ul> @foreach (var item in Model.Items) { <li>@item.Name - $@item.Price</li> } </ul>
View Example (Index.cshtml)
@model IEnumerable<MyApp.Models.User> @{ ViewData["Title"] = "User List"; } <h2>@ViewData["Title"]</h2> <p> <a asp-action="Create" class="btn btn-primary">Create New User</a> </p> <table class="table table-striped"> <thead> <tr> <th>@Html.DisplayNameFor(model => model.Name)</th> <th>@Html.DisplayNameFor(model => model.Email)</th> <th>@Html.DisplayNameFor(model => model.Age)</th> <th>Actions</th> </tr> </thead> <tbody> @foreach (var user in Model) { <tr> <td>@user.Name</td> <td>@user.Email</td> <td>@user.Age</td> <td> <a asp-action="Edit" asp-route-id="@user.Id">Edit</a> | <a asp-action="Details" asp-route-id="@user.Id">Details</a> | <a asp-action="Delete" asp-route-id="@user.Id">Delete</a> </td> </tr> } </tbody> </table>
Form Example
@model MyApp.Models.User <h2>Create User</h2> <form asp-action="Create" method="post"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Name" class="control-label"></label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Email" class="control-label"></label> <input asp-for="Email" class="form-control" /> <span asp-validation-for="Email" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Age" class="control-label"></label> <input asp-for="Age" class="form-control" /> <span asp-validation-for="Age" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> <a asp-action="Index" class="btn btn-secondary">Cancel</a> </div> </form> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }

ASP.NET vs PHP

ASP.NET

Advantages:

  • Strong typing and compile-time checking
  • Excellent IDE support (Visual Studio)
  • Built-in dependency injection
  • High performance
  • Enterprise-grade features
  • Great for large-scale applications

Considerations:

  • Steeper learning curve
  • Less hosting options than PHP
  • Traditionally Windows-centric (changing)
PHP

Advantages:

  • Easy to learn and get started
  • Ubiquitous hosting support
  • Massive ecosystem (WordPress, etc.)
  • Flexible and dynamic
  • Large community
  • Great for rapid development

Considerations:

  • Dynamically typed (can lead to bugs)
  • Less structure by default
  • Variable performance

Getting Started with ASP.NET

Prerequisites
  • .NET SDK: Download from microsoft.com/net
  • IDE: Visual Studio, VS Code, or Rider
  • Database: SQL Server, MySQL, PostgreSQL, or SQLite
Creating a New Project
# Create new MVC project dotnet new mvc -n MyWebApp # Navigate to project cd MyWebApp # Restore dependencies dotnet restore # Run the application dotnet run # Build for production dotnet build --configuration Release # Publish application dotnet publish --configuration Release
Project Structure
MyWebApp/ ├── Controllers/ # Application controllers │ └── HomeController.cs ├── Models/ # Data models │ └── User.cs ├── Views/ # Razor views │ ├── Home/ │ │ └── Index.cshtml │ └── Shared/ │ └── _Layout.cshtml ├── wwwroot/ # Static files (CSS, JS, images) │ ├── css/ │ ├── js/ │ └── lib/ ├── appsettings.json # Configuration ├── Program.cs # Application entry point └── Startup.cs # Application configuration
Entity Framework Core
using Microsoft.EntityFrameworkCore; namespace MyApp.Data { public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<User> Users { get; set; } public DbSet<Product> Products { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // Configure entity relationships modelBuilder.Entity<User>() .HasIndex(u => u.Email) .IsUnique(); } } } // Usage in Controller public class UsersController : Controller { private readonly ApplicationDbContext _context; public UsersController(ApplicationDbContext context) { _context = context; } public async Task<IActionResult> Index() { var users = await _context.Users.ToListAsync(); return View(users); } [HttpPost] public async Task<IActionResult> Create(User user) { if (ModelState.IsValid) { _context.Add(user); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(user); } }

Session Summary

Key Points
  • ASP.NET is Microsoft's modern, cross-platform web framework
  • Built on .NET, primarily using C# programming language
  • Implements MVC pattern for separation of concerns
  • Razor syntax enables embedding C# code in HTML
  • Entity Framework Core provides ORM capabilities
  • ASP.NET Core offers high performance and scalability
  • Excellent for enterprise applications and microservices
  • Strong typing and compile-time checking reduce bugs
  • Built-in dependency injection promotes testability
Next Session Preview

In the next session, we will explore APIs and Web Services, learning how to create and consume RESTful APIs, work with JSON, and integrate third-party services.