简体   繁体   中英

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.

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?

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. 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'); 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.

something like....

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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