Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Views in ASP.NET Core MVC

Suggested Videos
Part 18 - Model in ASP.NET Core MVC | Text | Slides
Part 19 - ASP.NET Core dependency injection tutorial | Text | Slides
Part 20 - Controller in ASP.NET Core MVC | Text | Slides

In this video we will discus, what is a View and it's role in the MVC design pattern.


View in MVC
  • Contains the logic to display the Model data provided to it by the Controller.
  • A view is an HTML template with embedded Razor markup.
  • A view file has .cshtml extension if the programming language is C#.

Where are View files stored
  • By default, MVC looks for view files in the Views folder
  • View files that belong to a specific controller are stored in a sub-folder in the Views folder and that sub-folder has the same name as the controller. 
  • The view file has the same name as that of the controller action method with a .cshtml extension
Example

For exammple, let's say, in our MVC project we have 2 controllers - HomeController and EmployeesController

HomeController has the following 3 action methods.
  • Index()
  • Details()
  • Edit()
EmployeesController has the following 3 action methods.
  • List()
  • Details()
  • Edit()
Views Folder Structure

The following diagram demonstrates views folder structure

asp.net mvc view folder structure
  • For each Controller we have a separate folder in the "Views" folder.
  • All the HomeController views are in Home folder in the "Views" folder.
  • All the EmployeesController views are in Employees folder in the "Views" folder.
  • Each view file has the same name as the controller action method.
Views Discovery

Consider the following HomeController. We have only one action method - Details(). The Details() action returns a View using the View() method. This View() method is provided by the Controller base class.

public class HomeController : Controller
{
    public ViewResult Details()
    {
        return View();
    }
}

Since we are returning a View from the action method that is named Details(), by default MVC looks for a view file with same name that has .cshtml extension. So in this case, it looks for Details.cshtml. It looks for this file in the following 3 locations in the order specified
  • First in "/Views/Home/" folder beacause the Controller name is HomeController
  • Then in "/Views/Shared/" folder
  • Finally in "/Pages/Shared/" folder
If a view file is found, the HTML generated by the view is sent back to the client who made the request. If the view file is not found we get the following error.

InvalidOperationException: The view 'Details' was not found. The following locations were searched:
/Views/Home/Details.cshtml
/Views/Shared/Details.cshtml
/Pages/Shared/Details.cshtml

asp.net core tutorial for beginners

No comments:

Post a Comment

It would be great if you can help share these free resources