简体   繁体   English

如何从剃刀部分引用JavaScript变量?

[英]How do I reference a javascript variable from a razor section?

I'm trying to dynamically render a CSS file to my view, but part of the location of the file is in a javascript variable. 我正在尝试将CS​​S文件动态呈现到视图中,但是文件的部分位置在javascript变量中。

Currently I have: 目前我有:

@section Styles {
    @{

        <link href="@Url.Content(Model.CssPath)" rel="stylesheet" type="text/css" />
     }
}

But I need to include the variable in the path, like this: 但是我需要在路径中包含变量,如下所示:

@section Styles {
    @{
       var pathPrefix = "somePath/";
        <link href="@Url.Content(pathPrefix + Model.CssPath)" rel="stylesheet" type="text/css" />
    }
}

I understand the server-side code is evaluated before the javascript variable exists, so how else do I accomplish this? 我了解到服务器端代码是在javascript变量存在之前进行评估的,那么我该怎么做?

First of all - why mixing client-side/server-side code? 首先-为什么要混合客户端/服务器端代码?

You cannot use JS variable along with server-side generated content because - as you said - it is executed on server before client's browsers hits JS code. 您不能将JS变量与服务器端生成的内容一起使用,因为-如您所说-它是在客户端的浏览器点击JS代码之前在服务器上执行的。 This is expected behavior. 这是预期的行为。

If this variable value can be determined on the server-side, you should move it there. 如果可以在服务器端确定此变量值,则应将其移到那里。

If it has to be generated on the client side, you can generate <link> tag using document.createElement('link'); 如果必须在客户端生成,则可以使用document.createElement('link');生成<link>标记document.createElement('link'); but it seems odd to me :) 但对我来说似乎很奇怪:)

Rather than trying to add the stylesheet via the razor view I would put the csspath into a javascript variable and then use jquery to combine it with the pathPrefix and append the stylesheet that way. 与其尝试通过razor视图添加样式表,不如将csspath放入javascript变量中,然后使用jquery将其与pathPrefix组合在一起,并以这种方式附加样式表。

something like.... 就像是....

<script>
    var cssPath = @Model.cssPath;
    var pathPrefix = "www.";
    $('head').append('<link rel="stylesheet" type="text/css" href="'+pathPrefix+cssPath+'">');
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM