I would like to change the CSS files on the fly (dynamically). I am developing in MVC 4 using Razor views. At the moment they are pulled from the web.config...
My bundle registration
bundles.Add(New StyleBundle("~/Content/themes/" + Domain.GetTheme + "/css").Include( "~/Content/themes/" + Domain.GetTheme + "/Main.css", "~/Content/themes/" + Domain.GetTheme + "/Content.css")) Razor View
@Styles.Render("~/Content/themes/" + Domain.GetTheme + "/css") Code in GetTheme property
Public Shared ReadOnly Property GetTheme As String Get Return ConfigurationManager.AppSettings("Theme") End Get End Property I'm not sure if this is the best way, but it works.
Research so far...
But now I want to change the theme on the fly. My initial idea was to access a querystring parameter. So if it contained ?Theme=Green then the CSS files would pick up the green version. The querystring value would be stored in session state so that the CSS would continue to use green until changed again via the querystring.
I started off by creating an attibute that I could apply to my controller...
Attribute
Public Class LoadThemeAttribute Inherits ActionFilterAttribute Public Overrides Sub OnActionExecuted(filterContext As ActionExecutedContext) MyBase.OnActionExecuted(filterContext) If HttpContext.Current.Request.QueryString("Theme") IsNot Nothing Then HttpContext.Current.Session("Theme") = HttpContext.Current.Request.QueryString("Theme") End If End Sub End Class Controller
<LoadTheme> Public Class CompanyController Inherits System.Web.Mvc.Controller ... End Class Then in my _Layout.vbhtml razor view I override the CSS files as follows:-
@If Session("Theme") IsNot Nothing Then @<link href="/Content/themes/@Session("Theme")/Main.css" rel="stylesheet"/> @<link href="/Content/themes/@Session("Theme")/Content.css" rel="stylesheet"/> Else @Styles.Render("~/Content/themes/" + Domain.GetTheme + "/css") End If I couldn't use the Render statement, I am assuming this is because this is called once when the project loads and cannot be called again. I certainly could not get it to work.
So my question is this:- Everything seems to work, but I just want to know if this is a good approach - is it a good MVC way to change the CSS files?