ASP.NET Core MVC

A Modern Web Framework for Building Scalable Applications

ASP.NET Core MVC is a powerful framework for building dynamic web applications using the Model-View-Controller design pattern. It provides a patterns-based way to build dynamic websites that enables a clean separation of concerns.

MVC Architecture

The Model-View-Controller (MVC) pattern separates an application into three main components:

Model

Represents the data and business logic of the application

View

Presents the user interface and displays data

Controller

Handles user input and interactions

Request Flow

ASP.NET Core MVC request handling process:

1. Request → 2. Routing → 3. Controller → 4. Model → 5. View → 6. Response

Key Features

Routing

Powerful URL mapping for SEO-friendly URLs

Tag Helpers

Server-side helpers to create and render HTML elements

Dependency Injection

Built-in support for loose coupling and testability

Razor Pages

Page-based programming model for simpler scenarios

Getting Started

Project Setup

# Create a new MVC project
dotnet new mvc -n MyWebApp

# Navigate to project directory
cd MyWebApp

# Run the application
dotnet run

Program.cs Configuration

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Folder Structure

MyWebApp/
├── Controllers/
├── Models/
├── Views/
├── wwwroot/
├── Program.cs
└── appsettings.json
Learn More

MVC Components in Detail

Model Example

using System.ComponentModel.DataAnnotations;

namespace MyWebApp.Models
{
    public class Product
    {
        public int Id { get; set; }
        
        [Required]
        [StringLength(100)]
        public string Name { get; set; }
        
        [Range(0.01, 1000)]
        public decimal Price { get; set; }
        
        [DataType(DataType.MultilineText)]
        public string Description { get; set; }
    }
}

Controller Example

using Microsoft.AspNetCore.Mvc;
using MyWebApp.Models;

namespace MyWebApp.Controllers
{
    public class ProductsController : Controller
    {
        // GET: Products/Index
        public IActionResult Index()
        {
            var products = new List
            {
                new Product { Id = 1, Name = "Laptop", Price = 999.99m },
                new Product { Id = 2, Name = "Mouse", Price = 19.99m }
            };
            
            return View(products);
        }
        
        // GET: Products/Details/5
        public IActionResult Details(int id)
        {
            var product = new Product { Id = id, Name = "Sample Product", Price = 49.99m };
            
            if (product == null)
            {
                return NotFound();
            }
            
            return View(product);
        }
    }
}

View Example (Razor Syntax)

@model IEnumerable

@{
    ViewData["Title"] = "Products";
}

Product List

@foreach (var item in Model) { }
@Html.DisplayNameFor(model => model.Name) @Html.DisplayNameFor(model => model.Price)
@Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.Price) Details

Advanced Topics

Dependency Injection

// Interface
public interface IProductService
{
    List GetProducts();
}

// Implementation
public class ProductService : IProductService
{
    public List GetProducts()
    {
        // Data access logic here
    }
}

// Registration in Program.cs
builder.Services.AddScoped();

// Usage in Controller
public class ProductsController : Controller
{
    private readonly IProductService _productService;
    
    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }
    
    public IActionResult Index()
    {
        var products = _productService.GetProducts();
        return View(products);
    }
}

Entity Framework Core Integration

// DbContext
public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions options)
        : base(options)
    {
    }
    
    public DbSet Products { get; set; }
}

// Registration in Program.cs
builder.Services.AddDbContext(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// Repository Pattern
public class ProductRepository : IProductRepository
{
    private readonly AppDbContext _context;
    
    public ProductRepository(AppDbContext context)
    {
        _context = context;
    }
    
    public IEnumerable GetProducts()
    {
        return _context.Products.ToList();
    }
}

Tip: ASP.NET Core MVC supports Web APIs too! You can build RESTful services alongside your web application using the same framework.