With razor, rendering a specific bundle of stylesheets is done with:
@Styles.Render("~/Content/css")
This refers to the BundleConfig
file which has the line:
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
... pointing to the site.css
file, inside the Content
folder.
I wanted to set a variable (I've tried a session variable) like this:
Session["cssTheme"] = "~/Content/css";
So I could put it in the Styles.Render
function, something like this:
@Styles.Render(@Session["cssTheme"])
But it gets an error of invalid arguments.
I wanted to do this so I could change the session variable value (to another style bundle) and that way change the css style of my web application.
So, how can I pass an edited variable into the Styles.Render
function?
First,
Session
is dynamic, meaning it can hold any type inside. When you just pull out a value, it's technically of typeobject
.Styles.Render
expects a parameter of typestring
, so you need to cast the value to astring
first:Then, there's the problem that you could potentially receive a null value if either that session variable is not set at all, or has been set to something other than a string value that can't be converted to a string. So, to compensate for that, you should provide some fallback for nulls:
Now, it will either use whatever is in the session variable, or "~/Content/css" as a last resort. Bear in mind though, that this is still pretty brittle. If
Session["cssTheme"]
is set to a string, but not a properly formatted bundle reference, you'll still get an error, and a runtime error at that, which is ugly. Ideally, you should have some sort of value sanitization routine that you runSession["cssTheme"]
through first before passing it toStyles.Render
.Lets say your model is MyModel and it has string property StyleSheet so you have your view like
Additionally you can get set this property from Session like below