View Conventions

In the last section, you have seen that how we can display a simple HTML page on user's browser using views in MVC. After the request we have made to load the Index page of the home controller, you may have wondered that how asp.net MVC found the correct view to render.

In HomeController.cs class, and inside Index Action method there is a single line which says,return View(). However, this statement is used to return the view, but if you will notice, we are not specifying the name of any view which we have to render. So how the Asp.Net MVC is returning the correct view?

Well, that is happening due to the implicit conventions in the ASP.NET MVC Framework, these conventions define the logic that how views can be rendered. If you will notice in the MVC project which we have created, you will see that the Controllers and Views are structured in a very specific manner.

For every controller there is specific View folder, like for HomeController there is a Home folder in the Views section, the same way for every action method inside HomeController there is a specific view in the Home folder which is inside Views folder.

So by looking at this structure, you can get an idea that how views are connected to the action methods.

When we request for a page or URL, Asp.Net MVC takes an appropriate action on it and finds the correct controller, once the controller has found it executes the logic to find the correct action method. Then if the Action Method is returning a view it executes the views selection logic and finds the correct view with the same name as action method inside /Views/ControllerName folder.

So for Index action methods the view file will be /Views/Home/Index.cshtml.

Overriding the views selection logic

In some cases, it is required to return a different view from the action method, Like if you want to return a different view from Index Action method, in that case, you can override the view's selection logic like below.

public ActionResult Index()
{
    return View("OtherViewNotIndex");
}

Returning a view present in a different directory

public ActionResult Index()
{
    return View("~/Views/OtherDirectoryName/ViewName.cshtml");
}