Can I specify a custom location to “search for views” in ASP.NET MVC?

后端 未结 10 2206
故里飘歌
故里飘歌 2020-11-22 06:08

I have the following layout for my mvc project:

  • /Controllers
    • /Demo
    • /Demo/DemoArea1Controller
    • /Demo/DemoArea2Controller
    • etc
10条回答
  •  孤街浪徒
    2020-11-22 06:16

    Now in MVC 6 you can implement IViewLocationExpander interface without messing around with view engines:

    public class MyViewLocationExpander : IViewLocationExpander
    {
        public void PopulateValues(ViewLocationExpanderContext context) {}
    
        public IEnumerable ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable viewLocations)
        {
            return new[]
            {
                "/AnotherPath/Views/{1}/{0}.cshtml",
                "/AnotherPath/Views/Shared/{0}.cshtml"
            }; // add `.Union(viewLocations)` to add default locations
        }
    }
    

    where {0} is target view name, {1} - controller name and {2} - area name.

    You can return your own list of locations, merge it with default viewLocations (.Union(viewLocations)) or just change them (viewLocations.Select(path => "/AnotherPath" + path)).

    To register your custom view location expander in MVC, add next lines to ConfigureServices method in Startup.cs file:

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure(options =>
        {
            options.ViewLocationExpanders.Add(new MyViewLocationExpander());
        });
    }
    

提交回复
热议问题