Introduction
In this article, we'll learn how to customize Razor Engine View location using IViewLocationExpander . IViewLocationExpander takes care of modifying the View locations and how the View Engine searches for path. Here are the best practices to set custom Razor View location in MVC. This feature was introduced in ASP.NET Core MVC.
You can create sub area in MVC. Read here for more details.
There are couple of APIs in IViewLocationExpander Interface.
IViewLocationExpander APIs
- ExpandViewLocations (ViewLocationExpanderContext, IEnumerable<String>) : this is invoked by Razor View Engine to determine the possible View locations . View Engine searches path in order it is added in the View locations, so the order of View locations does matter.
- PopulateValues(ViewLocationExpanderContext) : this is called every time so as to populate the route values .
Here, we have MyViews folder instead of Views and folder structure would be the same. MyViews folder is highlighted in red circle.
MyViewLocationExpander
ExpandViewLocations gets invoked while calling the action view each time. It provides Context and list of possible View locations path. You have to change all the possible locations with new location. Here, I'm changing the "Views" to "MyViews".
- /// <summary>
- /// My view location expander
- /// </summary>
- public class MyViewLocationExpander : IViewLocationExpander
- {
- public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context,
- IEnumerable<string> viewLocations)
- {
- //replace the Views to MyViews..
- viewLocations = viewLocations.Select(s => s.Replace("Views", "MyViews"));
- return viewLocations;
- }
- public void PopulateValues(ViewLocationExpanderContext context)
- {
- //nothing to do here.
- }
- }
- // This method gets called by the runtime. Use this method to add services to the container.
- public void ConfigureServices(IServiceCollection services)
- {
- //register the MyViewLocationExpander into ViewLocationExpanders
- services.Configure<RazorViewEngineOptions>(o => {
- o.ViewLocationExpanders.Add(new MyViewLocationExpander());
- });
- // Add framework services.
- services.AddMvc();
- }
Summery
In this write-up, we learned how we can customize the Razor View location and do awesome things with Razor View Engine.
References
https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.mvc.razor.iviewlocationexpander
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.

Wilson DevonlinePosted Mar 26, 2018, 9:59 AM
In Startup.cs you add the custom ViewLocationExpander, which works great. However, is there a way to add more locations during runtime?
wall rutlPosted Dec 15, 2017, 10:55 PM
Can someone give me and example of ASP.NET Core 2 Razor pages with SignalR