Passing variable into @Styles.Render function

2019-09-06 11:32发布

问题:

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?

回答1:

First, Session is dynamic, meaning it can hold any type inside. When you just pull out a value, it's technically of type object. Styles.Render expects a parameter of type string, so you need to cast the value to a string first:

@Styles.Render(@Session["cssTheme"] as String)

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:

@Styles.Render(@Session["cssTheme"] as String ?? "~/Content/css")

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 run Session["cssTheme"] through first before passing it to Styles.Render.



回答2:

Lets say your model is MyModel and it has string property StyleSheet so you have your view like

@model MyModel

@Styles.Render(model.StyleSheet) 

Additionally you can get set this property from Session like below

public StyleSheet {
get {
    if(Session["cssTheme"]!=null)
     return Session["cssTheme"] as String 
     else 
       return   "defaultTheme";
}
set 
{
Session["cssTheme"]=value;
}
}