Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

MVC Pattern

Overview

The Model-View-Controller (MVC) pattern is a design pattern used for developing web applications. It separates an application into three main components: the Model, the View, and the Controller. This separation helps manage complexity when building an application by dividing it into the following areas:

  • Model: The part of the application that handles the logic for the application's data.
  • View: The part of the application that handles the display of the data.
  • Controller: The part of the application that handles user interaction and updates the Model and View accordingly.

Getting Started

To start with ASP.NET Core MVC, you need to have the following prerequisites:

  • Install the .NET SDK from the official website.
  • An integrated development environment (IDE) like Visual Studio or Visual Studio Code.

Creating a New ASP.NET Core MVC Project

You can create a new ASP.NET Core MVC project using the .NET CLI or Visual Studio. Here, we'll use the .NET CLI:


dotnet new mvc -o MyMvcApp
cd MyMvcApp
dotnet run
    

This will create a new MVC application and run it. You can access it at http://localhost:5000.

Project Structure

The ASP.NET Core MVC project structure includes several important files and folders:

  • Program.cs: The main entry point of the application.
  • Startup.cs: Configures services and the app's request pipeline.
  • appsettings.json: Configuration settings for the application.
  • Controllers folder: Contains controller classes responsible for handling incoming HTTP requests.
  • Views folder: Contains the Razor view files used for rendering HTML.
  • Models folder: Contains classes that represent the data of the application.

Creating a Model

Models in MVC are the components of the application that handle data logic. They often represent the data to be used in the application. Here's an example of a simple model class:


namespace MyMvcApp.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}
    

Creating a Controller

Controllers in ASP.NET Core handle incoming HTTP requests and produce responses. Here's an example of a simple controller:


using Microsoft.AspNetCore.Mvc;
using MyMvcApp.Models;
using System.Collections.Generic;

namespace MyMvcApp.Controllers
{
    public class ProductController : Controller
    {
        public IActionResult Index()
        {
            var products = new List<Product>
            {
                new Product { Id = 1, Name = "Product1", Price = 10.0M },
                new Product { Id = 2, Name = "Product2", Price = 20.0M },
                new Product { Id = 3, Name = "Product3", Price = 30.0M },
            };

            return View(products);
        }
    }
}
    

Creating a View

Views in ASP.NET Core are used to render HTML. They are typically written using Razor syntax. Here's an example of a simple view for the Product model:


@model IEnumerable<MyMvcApp.Models.Product>

<h2>Product List</h2>

<table class="swf-lsn-table">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var product in Model)
        {
            <tr>
                <td>@product.Id</td>
                <td>@product.Name</td>
                <td>@product.Price</td>
            </tr>
        }
    </tbody>
</table>
    

Routing

ASP.NET Core MVC uses a powerful routing engine that can be used to define routes. By default, the routing is configured in the Startup.cs file. Here is an example of how to configure the routing:


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();

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

Dependency Injection

ASP.NET Core has built-in support for dependency injection (DI), which makes it easy to manage and inject dependencies. To add a service to the DI container, use the ConfigureServices method in Startup.cs:


public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddTransient<IMyService, MyService>();
}
    

Conclusion

The Model-View-Controller (MVC) pattern is a powerful design pattern that helps manage complexity when building web applications by separating concerns into distinct components. By following this tutorial, you have learned the basics of setting up an ASP.NET Core MVC project, creating models, views, and controllers, configuring routing, and using dependency injection.