Views in ASP.NET Core MVC

Views in ASP.NET Core MVC Application

In this article, I will discuss ASP.NET Core MVC Views with Examples. Please read our previous article before proceeding to this article, where we discussed Models in ASP.NET Core MVC Applications. As part of this article, we will discuss the following concepts related to Views in ASP.NET Core MVC Applications.

  1. What are Views in ASP.NET Core MVC Application?
  2. Roles of View.
  3. Where are View Files Stored in ASP.NET Core MVC Application?
  4. How to create View in ASP.NET Core?
  5. How do we return views from action methods?
  6. What is the difference between View() and View(object model) Extension Methods?
  7. How do you specify the Absolute view file path?
  8. How Does the Controller Action Method Identify the View in ASP.NET Core MVC?
What is a View in ASP.NET Core MVC Application?

In the Model-View-Controller (MVC) pattern, the View is the component that contains logic to represent the model data (the model data provided to it by a controller) as a user interface with which the end-user can interact. The Views in ASP.NET Core MVC are HTML templates with embedded Razor markup, which generate content that is sent to the client. In our upcoming articles, we will discuss the Razor syntax in detail.

A view in ASP.NET Core MVC Application is a file with a “.cshtml” (for C# language) extension. The meaning of cshtml = CS (C Sharp) + HTML. That means the view is a combination of programming language (C#) and HTML (Hypertext Mark-up Language). The Views in the ASP.NET Core MVC Application are generally returned from the Controller Action Method. 

What is the Role of View in the ASP.NET Core MVC Application?

A view in ASP.NET Core MVC Application is responsible for UI, i.e., application data presentation. That means we display information about the website on the browser using the views only. A user generally performs all the actions on a view, such as a button click, form, list, and other UI elements.

Views in the MVC Application are responsible for presenting content through the user interface. In the ASP.NET Core MVC Application, we use the Razor View Engine to embed .NET code in HTML markup. There should be minimal logic (you should not write any business logic, calculation logic, etc.) within views, and any logic in them should only be related to presenting the content. 

Where are Views Placed in ASP.NET Core MVC Application?

By default, Views are available inside the Views folder at the root. Usually, views are grouped into folder names with the applications controller. Each controller will have its own folder in which the controller-specific view files will be stored. The controller-specific folders are going to be created within the Views folder only. 

Let’s say we have an ASP.NET Core MVC application with two controllers, i.e., HomeController and StudentController. The HomeController is created with the following three action methods.

  1. AboutUs()
  2. ContactUs()
  3. Index()

On the other hand, the StudentController is created with the following four action methods.

  1. Index()
  2. Details()
  3. Edit()
  4. Delete()

Then, the following is the folder and file structure of the Views.

Where are views placed in ASP.NET Core MVC Application?

As you can see in the above image, a separate folder is created for each controller within the Views Folder. The Home folder represents the HomeController and the Student folder inside the Views folder represents the Student Controller.

The Home folder contains the views for the Index, AboutUs, and ContactUs webpages. So, whenever a user requests any of these web pages, the Home Controller action method determines which of the above three views to use to build the webpage and return to the user.

Similarly, the Student folder contains the Index, Details, Edit, and Delete web page views. So, whenever a user requests any of these web pages, the Student Controller action method determines which of the above views to use to build the webpage and return to the user.

Note: In addition to action-specific views, we have also provided partial views, layouts, and view components that can also be used to reduce the repetition and allow for reuse within the application’s views. We will discuss each of these in our upcoming articles.

Example to Understand Views in ASP.NET Core MVC Application:

We will work with the same example we created in our ASP.NET Core Controllers article and continue in Models in the ASP.NET Core article.

Adding Home Controller

We have already created one controller called Student Controller within the Controllers folder. Let us add a new Controller with the name HomeController. While creating the HomeController, you must select the MVC Controller – Empty template. At this time, your project folder structure should look like the one below.

Example to Understand Views in ASP.NET Core MVC Application

Open HomeController and then copy and paste the following code into it.

using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCWebApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View();
        }
    }
}

As you can see in the above HomeController class, we have only one action method, i.e., Index. As the return type of the Index() action method is ViewResult, this action method will return a view. In order to return a view, here we are using the View() extension method, which Microsoft provides.AspNetCore.Mvc.Controller Base class.

Note: Views are typically returned from the Action method as a ViewResult, which is a type of ActionResult. Your action method can create and return a ViewResult directly, but that isn’t commonly done. Since most ASP.NET Core MVC Controllers are inherited from the Controller base class, we can use the View helper method to return the ViewResult.

Now run the application and navigate to the “/Home/Index” URL or the default URL, and you will see the following error.

Views in ASP.NET Core MVC Application

Why did we get the Above Invalid Operation Exception?

Let us understand why we got the above exception. As we return a view from the Index action method of Home Controller, by default, the ASP.NET Core MVC Framework will look for a file with the name Index.cshtml in the following three locations.

  1. First, it will look for the “Index.cshtml” file within the “/Views/Home” folder, as the action method belongs to the Home Controller.
  2. Then it will look for the “Index.cshtml” file in the “/Views/Shared/” folder.
  3. Then it will look for the “Index.cshtml” file in the “/Pages/Shared/” folder.

If the requested “.cshtml” file is found in any of the above folders, then the View generates the HTML and sends the generated HTML back to the client who initially made the request. On the other hand, if the requested file is not found in any of the above locations, then we will get the above error.

Creating Index View

As we already discussed, views will be created in a special folder called Views. So, let us first add a folder to the project root level with the name Views. To do so, right-click on the Project and then select Add => New Folder from the context menu, which will add a new folder, and then rename the folder as Views.

As we already discussed, the Action Views will be created inside the folder whose name is the same as the Controller’s name. We want to create a view for the Index action method of the Home Controller. So, let us first add the Home folder inside the View folder. To do so, right-click on the Views folder and then select the Add => New Folder option, which will add a new folder, and then rename the folder as Home.

Once you have created the Home folder, then we need to create a view within this Home folder. In ASP.NET Core MVC, we can add views in many different ways, and we will discuss them one by one.

So, right-click on the Home folder and then select the Add => View option, which will open the Add View window, as shown in the image below. You must select the Razor View item and click the Add button, as shown in the image below.

Adding Razor View in ASP.NET Core MVC

Once you click the Add button, it will open the Add Razor View window. Here, you need to give the View name as Index, Select the Empty (without model) template, uncheck the create a partial view, use a layout page checkbox, and then click on the Add button as shown below.

Creating Views in .NET Core MVC Application

Once you click the Add button, it should create the Index.cshtml view within the Home folder, as shown in the below image.

Creating View in ASP.NET Core MVC

Now open Index.cshtml file and then copy and paste the following code into it.

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h1>Index view belongs to Views/Home folder</h1>
</body>
</html>

With the above changes in place, run the application, and you should get the output as expected, as shown in the image below.

Roles of View.

Understanding View() Method in ASP.NET Core MVC Application:

If you go to the definition of the Controller base class, you will find four overload versions of the View() method available, as shown in the image below.

Understanding View() Method in ASP.NET Core MVC Application:

Let us understand the use and significance of each of the above-overloaded versions of the View Extension method.

View() vs View(object model) Extension Methods:

If you use the View() or View(object model) extension method to return a view, it will look for the view file with the same name as the action method name. If you want to pass some model data, you need to use the overloaded version of the View method, which takes the object model as an input parameter; otherwise, you can use the View() extension method, which does not take any parameter.

For example, in the code below, we are using the View() extension method, which does not take any parameter to return a view from the Index action method of the Home Controller. So, in this case, by default, the ASP.NET Core MVC framework will look for a view with the name Index.cshtml within the “Views/Home” folder.

View() vs View(object model) Extension Methods:

View(string viewName) vs  View(string viewName, object model) Extension Methods:

If you want to return a view from an action method whose name is different than the action method name, then you need to use either View(string viewName) or View(string viewName, object model) Extension Methods. If you want to pass model data to the view, you need to use the View(string viewName, object model) method; otherwise, you can use the View(string viewName) method, which takes the view name as a parameter.

To understand this concept, let’s create a view with the name Test.cshtml within the Home folder. Please follow the same steps we follow to create the index.cshtml view. Once you created the Test.cshtml view, then open the Test.cshtml file and copy-paste the below code in it.

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Test</title>
</head>
<body>
    <h1>Test view coming from Views/Home Folder</h1>
</body>
</html>

Now, modify the Index action method of the HomeController class as shown below to use the View extension method, which takes the view name as a parameter.

using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCWebApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View("Test");
        }
    }
}

Now run the application and navigate to the “/Home/Index” URL, and you will see that the response is coming from the Test view, as shown in the image below.

View(string viewName) vs  View(string viewName, object model) Extension Methods

Note: You need to specify the view name without an extension. It is also possible to specify the file path using this overloaded version. You can specify either the absolute path or the relative path.

How do you specify the Absolute View File Path?

Let us modify the Index action method of the Home controller, as shown below, to specify the Absolute path of the view file. So here, the ASP.NET Core MVC framework will look for a view file with the name “Test.cshtml” within the “Views/Home” folder.

using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCWebApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View("Views/Home/Test.cshtml");
        }
    }
}

Note: When using the absolute path, it is mandatory to use the .cshtml extension.

When you are using an absolute path, in order to get to the project’s root directory, you can use / or ~/. So. you can use any of the following, and all will do the same thing.

How to specify the Absolute view file path?

Absolute Path vs Relative Path in ASP.NET Core While Specifying the View Name

In ASP.NET Core, when specifying the view name in a controller, you can use either an absolute path or a relative path. Understanding the difference between these two types of paths and when to use each is important for efficient and error-free coding.

Absolute Path:
  • An absolute path is a complete path from the root of the application to the view file. It usually starts with a forward slash (/) or a tilde and forward slash (~/), which represents the root of the web application.
  • Example: return View(“~/Views/Home/Index.cshtml”);
  • Use absolute paths when you want to specify the exact location of a view file without any ambiguity.
Relative Path
  • A relative path is relative to the location of the calling controller. In ASP.NET Core, the default convention is to look for views in a folder that matches the controller name within the Views folder.
  • Example: If you have a HomeController, calling return View(“Index”); will by default look for the view in Views/Home/Index.cshtml.
  • Relative paths are more concise and are generally preferred for standard view locations that follow the default MVC folder structure.
Best Practices:
  • Use relative paths when the views are located in the conventional locations (e.g., Views/[ControllerName]/[ViewName].cshtml).
  • Use absolute paths when you need to reference a view outside of the conventional locations or when you want to ensure the path remains valid regardless of controller location.
Another way of Creating Views:

Let us add a new action to the HomeController with the name About. So, please modify the HomeController as shown below.

using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCWebApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View();
        }
        public ViewResult About()
        {
            return View();
        }
    }
}

Now, right-click anywhere within the About action method and click on the Add View from the context menu, as shown in the image below.

How to return views from action methods?

Once you click on the Add View, it will open the Add New Scaffolded Item window, as shown below, where you need to select the Razor View and click on the Add button, as shown in the image below.

What are the Advantages of Using Views in ASP.NET Core MVC Application?

Once you click on the Add button, it will open the Add Razor View window, and by default, it will give the View name as About (action method name), and finally, click on the Add button as shown in the image below.

What are Views in ASP.NET Core MVC Application?

Once you click the Add button, it will add the About.cshtml file within the View/Home folder, as shown in the below image.

Views in ASP.NET Core MVC application

How Does the Controller Action Method Identify the View in ASP.NET Core MVC?

In ASP.NET Core MVC Web Application, when an action method of a controller returns a view, a process called View Discovery takes place. This View Discovery process determines which view file should be used based on the view name.

The default behavior of the View method (i.e., return View();) is to return a view with the same name as the action method name from which it is being called. For example, the Index ActionResult method of the Home controller is used to search for a view file with the name Index.cshtml in the following three locations.

  1. First, it will look for the “Index.cshtml” file within the /Views/Home, i.e., Views/[ControllerName] folder, as the action method belongs to the Home Controller.
  2. Then it will look for the “Index.cshtml” file in the “/Views/Shared/” folder.
  3. Then it will look for the “Index.cshtml” file in the “/Pages/Shared/” folder.

So, it doesn’t matter if you implicitly return the ViewResult with return View(); or explicitly pass the view name to the View method with return View(“<ViewName>”);. In both cases, view discovery searches for a matching view file in this order:

  1. Views/[ControllerName]/[ViewName].cshtml
  2. Views/Shared/[ViewName].cshtml
  3. Pages/Shared/[ViewName].cshtml

In the next article, I will discuss ASP.NET Core Dependency Injection with Examples. In this article, I try to explain Views in ASP.NET Core MVC Applications with Examples. I hope you enjoy this ASP.NET Core MVC Views with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *