【问题标题】:ASP .NET MVC 2: Dynamic themesASP .NET MVC 2:动态主题
【发布时间】:2011-01-14 16:35:17
【问题描述】:

我想在 MVC 2 应用程序中动态更改页面主题。 找到了几种解决方案,但我想用这个方法:在Global.asax中,更改当前页面主题:

   protected void Application_PreRequestHandlerExecute(object sender, System.EventArgs e)
    {
        // cast the current handler to a page object
        Page p = HttpContext.Current.Handler as Page;

        if (p != null)
        {
            string strTheme = "Theme1";
            if (Convert.ToString(HttpContext.Current.Session["THEME"]) != string.Empty)
                strTheme = Convert.ToString(HttpContext.Current.Session["THEME"]);
            p.StyleSheetTheme = strTheme;
        }
    }

但是这段代码总是在 "p" 中返回 null... 我也尝试过使用 HttpModule 中的事件 PreRequestHandlerExecute 和页面的 PreInit 事件的类似代码,但是代码

HttpContext.Current.Handler 作为页面

总是返回 null。

谁能帮帮我? 提前谢谢你。

【问题讨论】:

  • 此技术不适用于 MVC。
  • 您能简要解释一下原因吗,或者您有任何相关文档吗?谢谢。
  • 据我了解,在控制器确定要呈现哪个视图之前,页面(它是一个 ViewPage,但它确实派生自 Page)不存在。假设它在 MVC 中完全设置在上下文中,这将在管道中进行得很晚。老实说,我没有详细研究它,但我只是按照我对 MVC 工作原理的理解。我不确定你希望它做什么,因为你不能使用任何它会影响的 ASP.NET 控件。

标签: asp.net asp.net-mvc asp.net-mvc-2 themes


【解决方案1】:

我不使用烘焙主题,但我使用 jQuery UI 主题。我处理它的方式是在我的母版页中,我有从通用视图模型获取当前主题的逻辑。母版页是对此视图模型的强类型。公共视图模型属性从我的所有控制器继承的公共基本控制器中的用户首选项和其他来源更新。我在 OnActionExecuted 中执行此操作。我检查结果是否为 ViewResult,然后将 ActionExecutedContext.Result 属性上的 ViewData 的结果转换为我的公共视图模型并设置该属性。母版页使用该属性的值来构建 CSS 文件的 url。

型号

public abstract class CommonViewModel
{
    public string Theme { get; set; }
    // ...
}

控制器

public abstract class BaseController : Controller
{
     public override void OnActionExecuted( ActionExecutedContext context )
     {
           if (context.Result is ViewResult)
           {
               var model = ((ViewResult)context.Result).ViewData.Model as CommonViewModel;
               if (model != null)
               {
                    var preferences = ...get from database for current user...
                    model.Theme = preferences.Theme;
               }
           }
    }
}

Master 请注意,它使用自定义 HtmlHelper 来生成样式表链接,您可以 亲手做。

<%@ Master Language="C#"  Inherits="System.Web.Mvc.ViewMasterPage<...CommonViewModel>" >

<%: Html.Stylesheet( "themes/" + Model.Theme + ".css" ) %>

【讨论】:

  • 感谢您分享您的技术,我会调查它。
【解决方案2】:

您所说的技术适用于标准 asp.net,而不是 asp.net MVC。原因是(通常)asp.net MVC 不使用标准 asp.net 使用的 Web 控制模型,因此没有什么可以解释主题设置。

@tvanfosson 有一些很好的建议。请记住,使用 MVC,您可以更好地控制事物。但这也意味着您必须做更多的工作才能获得标准 asp.net 免费提供的一些功能。 MVC 使许多事情变得更容易,但这不是其中之一。

【讨论】:

    猜你喜欢
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    相关资源
    最近更新 更多