asp.net mvc 6 自定义View的位置

@CodingSolution

asp.net core, asp.net mvc6 项目中默认使用Razor ViewEngine,按"约定胜于配置"的原则,默认的项目结构是按Controller, Views, Model这样的文件结构来组织的,其中。
其中主所有的View放在了Views目录中。
如果需要改变View的位置,可以通过IViewLocationExpander接口来实现自定义,主要的是就是View的查找路径。

默认的项目文件结构是

/
/controllers/
/controllers/HomeController.cs
/Models/
/Models/SomeModel.cs
/Views/
/Views/shared/_layout.cshtml
/Views/Home/Index.cshtml

按模块重新组织后的项目,

/UI/
/UI/HOME/
/UI/HOME/controllers/
/UI/HOME/controllers/HomeController.cs
/UI/HOME/Models/SomeModel.cs
/UI/HOME/Views/Index.cshtml
/UI/SharedViews/_layout.cshtml

解决办法 就是 通过继承 IViewLocationExpander 接口,自定义一个View的发现路径(假设名为 MyViewLocationExpander.cs),如下。

    public class MyViewLocationExpander : IViewLocationExpander
    {
        public IEnumerable<string> ExpandViewLocations(
            ViewLocationExpanderContext context,
            IEnumerable<string> viewLocations)
        {
            yield return "~/UI/{1}/Views/{0}.cshtml";
            yield return "~/UI/{1}/{0}.cshtml";
            yield return "~/UI/SharedViews/{0}.cshtml";
        }

        public void PopulateValues(ViewLocationExpanderContext context)
        {
        }

然后在 startup.cs 中注册下

public void ConfigureServices(IServiceCollection services)
        {
            // ...
              services.AddMvc()
             .AddRazorOptions(razor =>
              {
                    razor.ViewLocationExpanders.Add(new IdSvrHost.UI.MyViewLocationExpander());
               });
             // ...
         }

效果如下

Paste_Image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容