zoukankan      html  css  js  c++  java
  • asp.net core 自定视图主题 实现IViewLocationExpander接口

    新建ThemeViewLocationExpander.cs 实现IViewLocationExpander接口

     /// <summary>
        /// 自定视图主题 实现IViewLocationExpander接口
        /// </summary>
        public class ThemeViewLocationExpander : IViewLocationExpander
        {
            public ThemeViewLocationExpander()
            {
            }
            /// <summary>
            /// 主题名称
            /// /Views/+ViewLocationExpanders
            /// </summary>
            public string ThemeName { get; set; } = "Default";
    
            public void PopulateValues([FromServices]ViewLocationExpanderContext context)
            {
                HttpContext httpcontext = context.ActionContext.HttpContext;
                string theme = httpcontext.Request.GetTheme();
                if (theme.IsNotNullOrEmpty())
                {
                    ThemeName = theme;
                }
                context.Values["theme"] = ThemeName;
            }
    
            /// <summary>
            /// 主题切换
            /// </summary>
            /// <param name="theme"></param>
            /// <returns></returns>
            public virtual IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context,
                                                                   IEnumerable<string> viewLocations)
            {
                string n = string.Empty;
                foreach (string item in viewLocations)
                {
                    n = item.ToLower();
                    if (!n.Contains("/shared"))
                    {
                        n = n.Replace("{1}", $"theme/{context.Values["theme"]}/{{1}}");
                    }
                    yield return n;
                }
    
            }
        }

     添加新的ViewLocationExpanders

     public class Startup{
      public virtual void ConfigureServices(IServiceCollection services)
            {
    services.AddMvc().AddRazorOptions(option =>
        {
            option.ViewLocationExpanders.Clear();
            option.ViewLocationExpanders.Add(new ThemeViewLocationExpander());
        })
        }
    }
    

      

     

  • 相关阅读:
    搞清楚C#中的值类型(基础类型)和引用类型
    构造动态SQL语句
    Json.net API及常用方法
    泛型代码中的default有何作用
    SQL 中的for xml path()的使用
    fastJosn和JackJson的区别
    箭头函数
    3篇文章初探MVC工作流程
    MVC传递Model之TempData、ViewData、ViewBag区别和用途
    .Net 提交页面,js修改的Label值会丢掉
  • 原文地址:https://www.cnblogs.com/SpeakHero/p/9634172.html
Copyright © 2011-2022 走看看