When setting up a basic MVC from the Visual Studio Template it will provide 'two' views - Index and Privacy.
These views are constructed from a layout template found at Shared/_Layout.cshtml.
The use of the Shared/_Layout.cshtml template is dictated by the _ViewStart.cshtml at the root of Views/.
The Views/Home/Index.cshtml contains some HTML and some c# code. The c# code sets the ViewData["Title"] value used to set the HTML <title> element in the page. Open Shared/_Layout.cshtml to see where this value is used in the template.
The default MVC set up creates a Controllers/HomeController file. This files 'controls' both the Index and Privacy views through two methods with names that match the views.
Public methods on a controller (except those with the [NonAction] attribute) are described as Actions. Actions can return anything, but frequently return an instance of IActionResult that produce a response. The action method is responsible for choosing what kind of response. Both of the above return Views. The View returned is the one that matches the name of the method.
How a View is selected by the Controller is known as routing. The URL request made is picked up by the controller and 'routed' to a view. The specifics for this was set out in the pattern defined in the startup.cs.
As such a call to https://localhost:5001/Home/Privacy is passed to the Controllers/HomeController and the Privacy() action called, that in turn calls the Views/Home/Privacy.cshtml view.
Lets put this in table format:
| URL Called | Contoller Called | Action / Method Called | View Used |
|---|---|---|---|
| localhost:5001/Home/Privacy | Controllers/HomeController.cs | Privacy() | Views/Home/Privacy |
| localhost:5001/Home/Index | Controllers/HomeController.cs | Index() | Views/Home/Index |
Naming conventions are important here. The HomeController will look for views in Views/Home
Note there are default values. The starter template set up Home as the default controller and Index as the default action. Therefore the home page can be called various ways:
| URL Called | Contoller Called | Action / Method Called | View Used |
|---|---|---|---|
| localhost:5001/Home/Index | Controllers/HomeController.cs | Index() | Views/Home/Index |
| localhost:5001/Home/ | Controllers/HomeController.cs | Index() | Views/Home/Index |
| localhost:5001/ | Controllers/HomeController.cs | Index() | Views/Home/Index |
Create a new method in the Controllers/HomeController for a view called News.
You will need to create a new view called News.
This can be viewed at https://localhost:5001/Home/News
Create a new Controller called Controllers/NewsController.
This will require to have a view file to be created at Views/News/Index. that can be viewed at https://localhost:5001/News/