ASP.NET MVC Tip #24 – Retrieve Views from Different Folders
In this tip, I demonstrate how you can retrieve a view from any folder in an ASP.NET MVC application. I show you how to use both specific paths and relative paths.
Until today, I thought that a controller action could return a view from only one of two places:
· Views\controller name
· Views\Shared
For example, if you are working with the ProductController, then I believed that you could only return a view from either the Views\Product folder or the Views\Shared folder. When looking through the source code for the ViewLocator class, I discovered that I was wrong. If you supply a “Specific Path” for a view, you can retrieve a view from any location in an ASP.NET MVC application.
The ProductController.Index() action in Listing 1 returns a view from the specific path ~\Confusing\ButWorks.aspx.
Listing 1 – ProductController.vb (VB.NET)
Public Class ProductController
Inherits Controller
Public Function Index() As ActionResult
Return View("~\Confusing\ButWorks.aspx")
End Function
End Class
Listing 1 – ProductController.cs (C#)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Tip24.Controllers
{
public class ProductController : Controller
{
public ActionResult Index()
{
return View( @"~\Confusing\ButWorks.aspx");
}
}
}
A specific path is a path that starts with either the character ~ or /. Any other path gets treated differently.
You also can use relative paths such as SubProduct\Details or SubProduct/Details. Either relative path will return a view located at Views\Product\SubProduct\Details.aspx. Listing 2 contains a complete code listing that illustrates using relative paths.
Listing 2 – ProductController.vb (VB.NET)
Public Class ProductController
Inherits Controller
Public Function Index() As ActionResult
Return View("SubProduct\Details")
End Function
End Class
Listing 2 – ProductController.cs (C#)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Tip24.Controllers
{
public class ProductController : Controller
{
public ActionResult Index()
{
return View(@"SubProduct\Details");
}
}
}
Now, I want to be the first to warn you that you should never, never, never use this tip (Please delete this entry from your news aggregator immediately). There is a good reason for following the conventions inherent in an MVC application. Placing your files in known locations makes it easier for everyone to understand your application.