美文网首页dotNET
asp.net mvc 6 自定义View的位置

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

作者: MienDo | 来源:发表于2016-03-23 19:22 被阅读621次

    @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

    相关文章

      网友评论

        本文标题:asp.net mvc 6 自定义View的位置

        本文链接:https://www.haomeiwen.com/subject/mmzllttx.html