自定义 ViewEngine ASP.NET MVC 3

2024-05-04

我正在为 ASP.NET MVC 的自定义视图引擎寻找最简单的解决方案。这样我就可以超越路径来寻找视图。

实际上,我正在尝试在我的解决方案中构建一个主题系统。我查看了网络,但发现了很难学习和实施的解决方案。

Thanks


这就是我用的。它在主题文件夹中查找视图。在构造函数的第一行设置主题名称。它还支持移动视图,但您需要 51 Degrees Mobi 之类的工具来为您提供移动浏览器详细信息。

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;

namespace Milkshake.Commerce.MvcClient.ViewEngines
{
    /// <summary>
    /// Milkshake Commerce specific ViewEngine.
    /// </summary>
    public class MilkshakeViewEngine : WebFormViewEngine
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MilkshakeViewEngine"/> class.
        /// </summary>
        public MilkshakeViewEngine()
        {
            string themeName = AppData.ThemeName;

            var masterLocationFormats = new List<string>();
            masterLocationFormats.Add("~/Views/Themes/" + themeName + "/{0}.master");
            masterLocationFormats.AddRange(MasterLocationFormats);

            MasterLocationFormats = masterLocationFormats.ToArray();

            var partialViewLocationFormats = new List<string>();
            partialViewLocationFormats.Add("~/Views/Themes/" + themeName + "/{1}/{0}.aspx");
            partialViewLocationFormats.Add("~/Views/Themes/" + themeName + "/{1}/{0}.ascx");
            partialViewLocationFormats.Add("~/Views/Themes/" + themeName + "/{0}.aspx");
            partialViewLocationFormats.Add("~/Views/Themes/" + themeName + "/{0}.ascx");
            partialViewLocationFormats.AddRange(PartialViewLocationFormats);

            PartialViewLocationFormats = partialViewLocationFormats.ToArray();

            var viewLocationFormats = new List<string>();
            viewLocationFormats.Add("~/Views/Themes/" + themeName + "/{1}/{0}.aspx");
            viewLocationFormats.Add("~/Views/Themes/" + themeName + "/{1}/{0}.ascx");
            viewLocationFormats.Add("~/Views/Themes/" + themeName + "/{0}.aspx");
            viewLocationFormats.Add("~/Views/Themes/" + themeName + "/{0}.ascx");
            viewLocationFormats.AddRange(ViewLocationFormats);

            ViewLocationFormats = viewLocationFormats.ToArray();
        }

        /// <summary>
        /// Gets the user-selected <see cref="UserExperiences"/> setting, or returns the defualt if no experience has been selected.
        /// </summary>
        /// <returns>Returns the user experience selected by the user.</returns>
        public static UserExperiences GetUserExperienceSelected()
        {
            HttpContext context = HttpContext.Current;
            UserExperiences userExperience = context.Request.Browser.IsMobileDevice ? UserExperiences.Mobile : UserExperiences.Desktop;
            var userExperienceCookie = context.Request.Cookies["UserExperience"];

            if (userExperienceCookie != null)
            {
                if (!String.IsNullOrWhiteSpace(userExperienceCookie.Value))
                {
                    Enum.TryParse<UserExperiences>(userExperienceCookie.Value, out userExperience);
                }
            }
            else
            {
                SetUserExperience(userExperience);
            }

            return userExperience;
        }

        /// <summary>
        /// Sets the user experience cookie.
        /// </summary>
        /// <param name="experience">The user experience.</param>
        public static void SetUserExperience(UserExperiences experience)
        {
            HttpContext context = HttpContext.Current;
            HttpCookie userExperienceCookie = context.Request.Cookies["UserExperience"];

            if (userExperienceCookie == null)
            {
                userExperienceCookie = new HttpCookie("UserExperience");
            }

            userExperienceCookie.Value = experience.ToString();
            userExperienceCookie.Path = "/";
            userExperienceCookie.Expires = DateTime.UtcNow.AddDays(30);

            context.Response.Cookies.Add(userExperienceCookie);
        }

        /// <summary>
        /// Finds the specified view by using the specified controller context and master view name.
        /// </summary>
        /// <remarks>This override is used to determine if the browser is a mobile phone.
        /// If so, and it is supported, we add the phone specific folder/view name to the existing viewname,
        /// which forces the ViewManager to find a Theme specific mobile view (specific for that phone), or just use the built in mobile view.</remarks>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="viewName">The name of the view.</param>
        /// <param name="masterName">The name of the master view.</param>
        /// <param name="useCache">true to use the cached view.</param>
        /// <returns>The page view.</returns>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="controllerContext"/> parameter is null (Nothing in Visual Basic).</exception>
        /// <exception cref="T:System.ArgumentException">The <paramref name="viewName"/> parameter is null or empty.</exception>
        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            ViewEngineResult result = null;
            var request = controllerContext.HttpContext.Request;
            var userExperience = GetUserExperienceSelected();

            // Avoid unnecessary checks if this device isn't suspected to be a mobile device
            if (userExperience == UserExperiences.Mobile)
            {
                masterName = "Mobile/Mobile";
                result = base.FindView(controllerContext, "Mobile/" + viewName, masterName, useCache);
            }

            // Fall back to desktop view if no other view has been selected
            if (result == null || result.View == null)
            {
                result = base.FindView(controllerContext, viewName, masterName, useCache);
            }

            return result;
        }

        /// <summary>
        /// Adds the default mobile location formats.
        /// </summary>
        /// <param name="defaultLocationFormats">The default location formats.</param>
        /// <param name="viewLocationFormats">The view location formats.</param>
        private void AddDefaultMobileLocationFormats(string[] defaultLocationFormats, List<string> viewLocationFormats)
        {
            var mobileViewLocationFormats = new List<string>();

            foreach (var item in defaultLocationFormats)
            {
                if (item.Contains("Views/{1}/{0}"))
                {
                    mobileViewLocationFormats.Add(item.Replace("/{1}/{0}", "/{1}/Mobile/{0}"));
                }
                else if (item.Contains("Views/Shared/{0}"))
                {
                    mobileViewLocationFormats.Add(item.Replace("/Shared/{0}", "/Shared/Mobile/{0}"));
                }
            }

            viewLocationFormats.AddRange(mobileViewLocationFormats);
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

自定义 ViewEngine ASP.NET MVC 3 的相关文章

随机推荐

  • 将 POSIXct 日期值更改为每周的第一天

    我想计算平均值Dist每周使用这些数据 如下 同时保留使用POSIXct时间课 df lt structure list IndID structure c 1L 1L 1L 1L 1L 1L 1L 1L 1L 1L 1L 1L 1L 1L
  • 如何将一个窗格连接到另一个窗格

    如何将输出连接到paneWithList PaneWithList其上有一个监听器JList以便将所选行输出到控制台 我怎样才能将该输出定向到JTextPane关于输出 Could PaneWithList触发一个事件Main拿起 会属性更
  • 使用 RSelenium 下载嵌入到框架中的文件

    我正在参与一个项目 其中有一个网页 我需要单击该网页才能获取 pdf 文件 该文件出现在同一页面内的新窗口中 我认为是 iframe 然后我需要单击一个按钮来下载文件 我正在使用的代码如下 library wdman library RSe
  • Firebase Auth:如何检测 Firebase 尝试自动登录当前用户?

    我在用着firebase auth onAuthStateChanged 在浏览器中检测用户是否已登录 并在每个页面上加载 firebase 尝试登录当前用户 可能基于 IndexDB 中存储的令牌 我需要检测 firebase 何时尝试自
  • 与 ssh2_connect() 断开连接

    我已经使用 ssh2 连接ssh2 connect到服务器 但我没有看到任何方法在联机帮助页中 http php net ssh2 connect我应该如何结束连接 我不太喜欢在断开连接之前等待脚本结束 我可以用吗fclose 这听起来不对
  • 淡化背景但不淡化文本

    我已经对 div 应用了 CSS 淡入 淡出解决方案 在很大程度上我对此感到满意 但是我只想将其应用于背景 而不是文本 我需要文本始终完全不透明 参见示例 http jsfiddle net howiepaul gUAPV 33 http
  • bash 调整图像尺寸以适合特定大小

    我到处搜索但找不到这个问题的答案 我想精确输出一个文件夹中的所有图像 大小为 50Kb 并保持原始的宽高比 I tried ImageMagick并将大小调整为 250x250 例如 但它对我不起作用 它所做的是更改第一个尺寸并适应另一个尺
  • 在 R 中使用 NA 计算栅格数据的变异函数

    Summary 我有一个包含 NA 值的栅格数据集 并且想要计算它的变异函数 忽略 NA 我怎样才能做到这一点 我有一个图像 已使用以下命令加载到 R 中readGDAL函数 存储为im 为了使其可重复 结果dput图像上可在https g
  • 有用的库存 SQL 数据集吗?

    有谁知道有哪些资源可以提供优质 有用的股票数据集 例如 我下载了一个包含美国所有州 城市和邮政编码的 SQL 脚本 这在最近的一个应用程序中节省了我很多时间 我希望能够按地理位置进行查找 你们中有人知道其他可以免费下载的有用数据集吗 例如
  • Struts 未处理的异常 - 没有为操作定义结果 - Struts Spring 和 hibernate 集成

    实际上 我正在致力于在在线考试项目上实现 Struts Spring 和 Hibernate 集成 但是当我在 JSP 页面中提交值时 它会抛出以下错误 Struts 问题报告 Struts has detected an unhandle
  • 配置错误:无法链接到 boost_system

    我正在尝试在 Debian 上安装一个软件包 足球模拟器 2d 当我进入目录并运行时 configure 我得到以下信息 reza debian soccer rcssserver 15 0 1 configure checking for
  • 显示不同表中的名称而不是 ID

    我有 2 张桌子 Category带主键ID和列Name Employee带主键ID和列Category id Note Category id现在显示ID正确地 我想展示Name代替ID对于输出Employee Attempt categ
  • 将 CassandraUnit 与 Astyanax 结合使用时出现依赖性问题

    我有一个 SessionDaoCassandraImpl 类 它使用 Astyanax 从 Cassandra 读取数据 我想使用嵌入式 Cassandra 服务器进行测试 卡桑德拉单元 https github com jsevellec
  • ServiceStack 验证并不总是触发

    因此 我尝试使用 RavenDB 和 ServiceStack 构建端到端集成测试套件 但遇到了一个非常奇怪的问题 即验证无法对某些请求运行 这真的很奇怪 我不确定我做错了什么 我正在使用 NCrunch 有时测试通过 有时失败 希望这是一
  • Pyside QPushButton 和 matplotlib 的连接

    我正在尝试使用 matplotlib 开发一个非常简单的 pyside Qt 程序 我希望按下按钮时绘制图表 到目前为止 我可以在构造函数上绘制一些东西 但无法将 Pyside 事件与 matplotlib 连接起来 有没有办法做到这一点
  • 为什么链接生命周期仅与可变引用相关?

    前几天 有一个问题 https stackoverflow com questions 32089410 lifetimes and references to objects containing references有人对包含借用数据本
  • 如何在 CRUD 功能中映射复合键

    我需要基于两个键 comp 和part 进行映射 foreach var item in Model tr td Html DisplayFor modelItem gt item comp td td Html DisplayFor mo
  • Firefox 中的相对位置[重复]

    这个问题在这里已经有答案了 可能的重复 Firefox 是否支持表格元素上的position relative https stackoverflow com questions 5148041 does firefox support p
  • C++11 类型推导与 const char *

    In GotW 94 http herbsutter com 2013 08 12 gotw 94 solution aaa style almost always auto Herb Sutter 对 经典 C 声明进行了区分 const
  • 自定义 ViewEngine ASP.NET MVC 3

    我正在为 ASP NET MVC 的自定义视图引擎寻找最简单的解决方案 这样我就可以超越路径来寻找视图 实际上 我正在尝试在我的解决方案中构建一个主题系统 我查看了网络 但发现了很难学习和实施的解决方案 Thanks 这就是我用的 它在主题