将变量传递给@Styles.Render 函数 [英] Passing variable into @Styles.Render function
问题描述
使用 razor,渲染一组特定的样式表是通过以下方式完成的:
With razor, rendering a specific bundle of stylesheets is done with:
@Styles.Render("~/Content/css")
这指的是 BundleConfig
文件,其中包含以下行:
This refers to the BundleConfig
file which has the line:
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
... 指向 site.css
文件,位于 Content
文件夹内.
... 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";
所以我可以把它放在 Styles.Render
函数中,像这样:
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.
我想这样做是为了我可以更改会话变量值(到另一个样式包),从而更改我的 Web 应用程序的 css 样式.
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.
那么,如何将编辑过的变量传递给 Styles.Render
函数?
So, how can I pass an edited variable into the Styles.Render
function?
推荐答案
首先,Session
是动态的,这意味着它可以容纳任何类型.当您只提取一个值时,它在技术上属于 object
类型.Styles.Render
需要一个 string
类型的参数,因此您需要先将该值转换为 string
:
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")
现在,它要么使用会话变量中的任何内容,要么使用~/Content/css"作为最后的手段.但请记住,这仍然很脆弱.如果 Session["cssTheme"]
设置为字符串,但不是格式正确的包引用,您仍然会收到错误,并且会出现运行时错误,这很丑陋.理想情况下,您应该有某种值清理例程,在将其传递给 Styles.Render
之前先运行 Session["cssTheme"]
.
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
.
这篇关于将变量传递给@Styles.Render 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!