Back to: ASP.NET Core Tutorials For Beginners and Professionals
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 one, where we discussed Models in ASP.NET Core MVC Applications. In this article, we will discuss the following concepts related to Views in ASP.NET Core MVC Applications.
- What are Views in ASP.NET Core MVC Application?
- Where are View Files Stored in ASP.NET Core MVC Application?
- How to create View in ASP.NET Core?
- How do we return views from action methods?
- What is the difference between View() and View(object model) Extension Methods?
- How do you specify the Absolute view file path?
- 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 Model-View-Controller (MVC) Design 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. That means View is used to render the user interface. Views are the components in ASP.NET Core MVC that handle the application’s presentation logic. They are responsible for rendering HTML markup sent to the client’s browser, typically written using the Razor syntax.
A view in ASP.NET Core MVC Application is a file with “.cshtml” (for C# language) extension. The meaning of cshtml = CS (C Sharp) + HTML. The View combines programming language (C#) and HTML (Hypertext Mark-up Language). The Views in the ASP.NET Core MVC Application are generally returned to the client from the Controller Action Method.
Types of Views in ASP.NET Core MVC:
In ASP.NET Core MVC, there are four Types of Views. They are as follows:
- Razor Views: These are the most common views in ASP.NET Core MVC. They use the Razor syntax (.cshtml files), which is a combination of HTML and C#.
- Partial Views: These are reusable view components that can be embedded within other views. They are useful for rendering common elements like headers, footers, or navigation menus.
- View Components: These are similar to partial views but more powerful. They can encapsulate both the view and the logic needed to generate it.
- Layout Views: These provide a consistent look and feel across multiple views in your application. They define a common template for your pages, including headers, footers, and navigation bars. They define a common structure (like master pages in ASP.NET Web Forms).
Where are Views Placed in ASP.NET Core MVC Application?
By default, Views are available inside the Views folder, created in the project root directory. Usually, views are grouped into folder names with the controller names. Each controller will have its own folder in which the controller-specific view files will be stored. The controller-specific folders will be created only within the Views folder.
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.
- AboutUs()
- ContactUs()
- Index()
On the other hand, StudentController is created with the following four action methods.
- Index()
- Details()
- Edit()
- Delete()
Then, the following is the folder and file structure of the Views.
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 represents the Student Controller.
- The Home folder contains the views for the Index, AboutUs, and ContactUs webpages. Whenever a user requests one of these web pages, the Home Controller action method determines which of the above three views to use to build the webpage and return it 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: Besides action-specific views, we have also provided partial views, layouts, and view components. 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 a Controller called Student Controller in the Controllers folder. Let us add a new Controller named HomeController within the Controllers folder. At this time, your project folder structure should look like the one below.
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, Index. The return type of the Index() action method is ViewResult, which means it will return a view. To return a view, we use the View() extension method, which belongs to the 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.
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.
- First, it will look for the “Index.cshtml” file within the “/Views/Home” folder, as the action method belongs to the Home Controller.
- Then it will look for the “Index.cshtml” file in the “/Views/Shared/” folder.
- 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, the View generates the HTML and sends it 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, 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 select Add => New Folder from the context menu. This will add a new folder, which we will then rename 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 to add a new folder. Then, rename the folder 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 need to select the Razor View and click the Add button, as shown in the image below.
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 creation of a partial view, use a layout page checkbox, and then click on the Add button as shown below.
Once you click the Add button, the Index.cshtml view should be created within the Home folder, as shown in the image below.
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 expected output, as shown in the image below.
What is View Discovery in ASP.NET Core MVC?
View Discovery in ASP.NET Core MVC is the process by which the framework determines which view file to use when rendering a response to an HTTP request. This involves locating the appropriate view file based on the action method and controller that handles the request.
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.
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 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, by default, the ASP.NET Core MVC framework will look for a view with the name Index.cshtml within the “Views/Home” folder.
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) 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"); } } }
Run the application and navigate to the “/Home/Index” URL. As shown in the image below, the response comes from the test view.
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, the .cshtml extension is mandatory.
When using an absolute path to reach the project’s root directory, you can use / or ~/. You can also use any of the following, which will do the same thing.
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 or 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 application’s root to the view file. It usually starts with a forward slash (/) or a tilde and forward slash (~/), which represents the web application’s root.
- Example: return View(“~/Views/Home/Index.cshtml”);
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.
When to Use:
- Use relative paths when the views are located in the conventional locations (e.g., Views/[ControllerName]/[ViewName].cshtml).
- Use absolute paths when referencing a view outside the conventional locations or 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.
Once you click on the Add View, it will open the Add New Scaffolded Item window, as shown below. In this window, you need to select the Razor View and click the Add button, as shown in the image below.
Once you click on the Add button, the Add Razor View window will open. By default, the View will be named About (action method name). Finally, click the Add button, as shown in the image below.
Once you click the Add button, it will add the About.cshtml file within the View/Home folder, as shown in the below image.
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 article on ASP.NET Core MVC Views with Examples.