MVC

MVC

What is MVC?

The Model-View-Controller (MVC) is an architectural pattern that separates an application into three main logical components: the model, the view, and the controller. Each of these components is built to handle specific development aspects of an application.
MVC stands for Model, View, and Controller. MVC separates the application into three components
  • Model: Responsible for maintaining application data and business logic.
  • View: The user interface of the application, which displays the data.
  • Controller: Handles users' requests and renders appropriate view with model data.

Create MVC App

To start, we will create an ASP.NET Core web application project. The project type comes with all template files to create a web application before adding anything. Let's open Visual Studio 2019, if you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
On the start window, choose Create a new project.
On the Create a new project window, enter or type asp.net in the search box. Next, choose C# from the Language list, and then choose Windows from the Platform list. Select the ASP.NET Core Web Application template, and then choose Next.
In the Configure your new project window, type or enter EFCore5InMvcApp in the Project name box and click on the Create button.
In the Create a new ASP.NET Core web application window, verify that ASP.NET Core 5.0 appears in the top drop-down menu. Then, choose ASP.NET Core Web App (Model-View-Controller)\, including example ASP.NET Core MVC Views and Controllers, and then click on the Create button.
Visual Studio opens your new project and includes the default code files in your project as shown in the Solution Explorer.

Install Entity Framework Core

To use Entity Framework Core we need to install Microsoft.EntityFrameworkCore library. It is available as a nuget package and you can install it using Nuget Package Manager.
In the Package Manager Console window, enter the following command.
1
PM> Install-Package Microsoft.EntityFrameworkCore
Copied!
For SQL Server LocalDB, which is installed with Visual Studio, we need to install Microsoft.EntityFrameworkCore.SqlServer and will get all the packages required for EF Core.
1
PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer
Copied!
We also need to install the following NuGet package.
1
PM> Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design
Copied!

Create a Data Model and Database Context

In Solution Explorer, right-click on the Models folder and choose Add > Class. Enter a class file name Author.cs and add the following code.
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Threading.Tasks;
5
​
6
namespace EFCore5InMvcApp.Models
7
{
8
public class Author
9
{
10
public int AuthorId { get; set; }
11
public string FirstName { get; set; }
12
public string LastName { get; set; }
13
public DateTime BirthDate { get; set; }
14
public virtual ICollection<Book> Books { get; set; }
15
}
16
}
Copied!
Now let's add another entity class Book and replace the following code.
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Threading.Tasks;
5
​
6
namespace EFCore5InMvcApp.Models
7
{
8
public class Book
9
{
10
public int Id { get; set; }
11
public string Title { get; set; }
12
public int AuthorId { get; set; }
13
public Author Author { get; set; }
14
}
15
}
Copied!
So let's create a folder in your project by right-clicking on your project in Solution Explorer and click Add > New Folder. Name the folder DAL (Data Access Layer). In that folder, create a new class file named BookStore.cs, and replace the following code.
1
using EFCore5InMvcApp.Models;
2
using Microsoft.EntityFrameworkCore;
3
using System;
4
using System.Collections.Generic;
5
using System.Linq;
6
using System.Threading.Tasks;
7
​
8
namespace EFCore5InMvcApp.DAL
9
{
10
public class BookStore : DbContext
11
{
12
public BookStore(DbContextOptions<BookStore> options) : base(options)
13
{
14
}
15
public DbSet<Author> Authors { get; set; }
16
public DbSet<Book> Books { get; set; }
17
}
18
}
Copied!

Register Context Class

To register BookStore as a service, open Startup.cs, and call the AddDnContext in the ConfigureServices method.
1
// This method gets called by the runtime. Use this method to add services to the container.
2
public void ConfigureServices(IServiceCollection services)
3
{
4
services.AddDbContext<BookStore>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
5
services.AddControllersWithViews();
6
}
Copied!
The name of the connection string is passed into the context by calling a method on a DbContextOptionsBuilder object.

Setup Connection String

For local development, the ASP.NET Core configuration system reads the connection string from the appsettings.json file. So let's add the connection to that file as shown below.
1
{
2
"ConnectionStrings": {
3
"DefaultConnection": "Data Source=(localdb)\\ProjectsV13;Initial Catalog=BookStoreDb;Trusted_Connection=True;MultipleActiveResultSets=true"
4
},
5
"Logging": {
6
"LogLevel": {
7
"Default": "Information",
8
"Microsoft": "Warning",
9
"Microsoft.Hosting.Lifetime": "Information"
10
}
11
},
12
"AllowedHosts": "*"
13
}
Copied!
The above connection string specifies that the Entity Framework will use a LocalDB database named BookStoreDb.

Initialize Database

The Entity Framework will create an empty database for you. So we need to write a method that's called after the database is created to populate it with test data.
In the DAL folder, add a new class BookStoreInitializer and replace the following code.
1
using EFCore5InMvcApp.Models;
2
using System;
3
using System.Collections.Generic;
4
using System.Linq;
5
using System.Threading.Tasks;
6
​
7
namespace EFCore5InMvcApp.DAL
8
{
9
public class BookStoreInitializer
10
{
11
public static void Initialize(BookStore context)
12
{
13
​
14
context.Database.EnsureCreated();
15
​
16
// Look for any authors.
17
if (context.Authors.Any())
18
{
19
return; // DB has been seeded
20
}
21
​
22
var authors = new List<Author>
23
{
24
new Author { FirstName="Carson", LastName="Alexander", BirthDate = DateTime.Parse("1985-09-01")},
25
new Author { FirstName="Meredith", LastName="Alonso", BirthDate = DateTime.Parse("1970-09-01")},
26
new Author { FirstName="Arturo", LastName="Anand", BirthDate = DateTime.Parse("1963-09-01")},
27
new Author { FirstName="Gytis", LastName="Barzdukas", BirthDate = DateTime.Parse("1988-09-01")},
28
new Author { FirstName="Yan", LastName="Li", BirthDate = DateTime.Parse("2000-09-01")},
29
};
30
​
31
authors.ForEach(a => context.Authors.Add(a));
32
context.SaveChanges();
33
​
34
var books = new List<Book>
35
{
36
new Book { Title = "Introduction to Machine Learning", AuthorId = 1 },
37
new Book { Title = "Advanced Topics in Machine Learning", AuthorId = 1 },
38
new Book { Title = "Introduction to Computing", AuthorId = 1 },
39
new Book { Title = "Introduction to Microeconomics", AuthorId = 2 },
40
new Book { Title = "Calculus I", AuthorId = 3 },
41
new Book { Title = "Calculus II", AuthorId = 3 },
42
new Book { Title = "Trigonometry Basics", AuthorId = 4 },
43
new Book { Title = "Special Topics in Trigonometry", AuthorId = 4 },
44
new Book { Title = "Advanced Topics in Mathematics", AuthorId = 4 },
45
new Book { Title = "Introduction to AI", AuthorId = 4 },
46
};
47
​
48
books.ForEach(b => context.Books.Add(b));
49
context.SaveChanges();
50
}
51
}
52
}
Copied!
  • The above code creates a database when needed and loads test data into the new database.
  • It also checks if there are any authors in the database, and if not, it assumes the database is new and needs to be seeded with test data.
In Program.cs file, replace the following code in the Main method.
1
using EFCore5InMvcApp.DAL;
2
using Microsoft.AspNetCore.Hosting;
3
using Microsoft.Extensions.Configuration;
4
using Microsoft.Extensions.DependencyInjection;
5
using Microsoft.Extensions.Hosting;
6
using Microsoft.Extensions.Logging;
7
using System;
8
using System.Collections.Generic;
9
using System.Linq;
10
using System.Threading.Tasks;
11
​
12
namespace EFCore5InMvcApp
13
{
14
public class Program
15
{
16
public static void Main(string[] args)
17
{
18
var host = CreateHostBuilder(args).Build();
19
​
20
using (var scope = host.Services.CreateScope())
21
{
22
var services = scope.ServiceProvider;
23
try
24
{
25
var context = services.GetRequiredService<BookStore>();
26
BookStoreInitializer.Initialize(context);
27
}
28
catch (Exception ex)
29
{
30
var logger = services.GetRequiredService<ILogger<Program>>();
31
logger.LogError(ex, "An error occurred while seeding the database.");
32
}
33
}
34
​
35
host.Run();
36
}
37
​
38
public static IHostBuilder CreateHostBuilder(string[] args) =>
39
Host.CreateDefaultBuilder(args)
40
.ConfigureWebHostDefaults(webBuilder =>
41
{
42
webBuilder.UseStartup<Startup>();
43
});
44
}
45
}
Copied!
On application startup, the Main method does the following operations.
  • Get a database context instance from the dependency injection container.
  • Call the seed method, passing to it the context.
  • Dispose of the context when the seed method is done.

Create Controller and Views

MVC controllers are responsible for responding to requests made against your website. Each browser request is mapped to a particular controller.
To create a controller, right-click the Controllers folder in Solution Explorer, and select Add > Controller...
It will open the Add Scaffold dialog box.
Select MVC Controller with views, using Entity Framework, and then click the Add button.
In the Add MVC Controller with views, using Entity Framework dialog box, select Author (EFCore5InMvcApp.Models) from the Model class and BookStore (EFCore5InMvcApp.DAL) from the Data context class dropdown.
Enter AuthorController (not AuthorsController) as a Controller name and click the Add button.
The scaffolder creates an AuthorController.cs file and a set of views (.cshtml files) that work with the controller.

Setup Menu Options

Open Views\Shared\_Layout.cshtml, and add a menu entry for Authors after the Home menu option as shown below.
1
<header>
2
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
3
<div class="container">
4
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">EFCore5InMvcApp</a>
5
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
6
aria-expanded="false" aria-label="Toggle navigation">
7
<span class="navbar-toggler-icon"></span>
8
</button>
9
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
10
<ul class="navbar-nav flex-grow-1">
11
<li class="nav-item">
12
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
13
</li>
14
<li class="nav-item">
15
<a class="nav-link text-dark" asp-area="" asp-controller="Author" asp-action="Index">Authors</a>
16
</li>
17
<li class="nav-item">
18
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
19
</li>
20
</ul>
21
</div>
22
</div>
23
</nav>
24
</header>
Copied!
Press Ctrl+F5 to run the project, click the Authors tab to see the test data.
Last modified 4mo ago