I thought that the introduction was great, and I wanted to create some notes around the core concepts introduced in the first major chapter, MVC Basics. There was a lot of information and I wanted to break everything down for my own personal knowledge and reference.
Key ConceptsMVC is a coding pattern heavily in use today which segments the code making it decoupled and less complex.
MVC stands for:
- Model - Models hold data that is added to views (These are called view models) or data that is entered by the user.
- View - Views are HTML Templates + a Templating language such as Razor (In a word Razor is Csharp + HTML)
- Controller - Controllers handle requests and make decision about which code to run.
The following files are created or edited
- Located under Controllers/TodoController.cs
- This file creates a route to /Todo under the website. The /Index action is not listed in the URL as is the default behavior of ASP.NET core.
- This file is the main controller file. As outlined by the comments this controller does the following:
- //get todo items from database.
- This ties everything in by using the Interface named ITodoItemService which uses the FakeTodoItemService service to pull in the hardcoded example tasks. These tasks are modeled by the TodoItem model.
- //put items into a model
- Create a new view model named TodoViewModel with the todoItems pulled from the ITodoItemService interface.
- //Render view using the model
- using the return statement it renders the view using the TodoViewModel.
- Located under Models/TodoItem.cs
- This is the "entity" or model representing the items stored in the database.
- four properties of the class are defined each with getter / setter methods.
- Id (Guid)
- IsDone (bool)
- Title (String)
- DueAt (nullable datetimeoffset)
- Located under Models/TodoViewModel.cs
- This is the view model.
- As the TodoItem only represents a single item, the TodoViewModel represents an array of the TodoItem entities.
- Located under Views/Todo/Index.cshtml
- The view first uses the @model to bind the view model of the TodoViewModel
- There is a for each statement that displays the Title and Due in a new row for each item in the array.
- Located under wwwroot/css/site.css
- The Site.CSS is edited to add some styling to the CSS elements used in the view.
- Located under Services/ITodoItemService.cs
- This interface defines a definition or method signature for getting incomplete items, the GetIncompleteItemsAsync method.
- Located under Services/FakeTodoItemService.cs
- This service is a fake service which always returns the same two items.
- This service implements the ITodoItemService.
- Located under the root of the project.
- You must specify that the FakeTodoItemService is used for the ITodoItemService interface.
- This is done with dependency Injection.