0

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?

Daniel Minnaar
  • 5,865
  • 5
  • 31
  • 52

2 Answers2

1

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 :)

kamil-mrzyglod
  • 4,948
  • 1
  • 20
  • 29
  • You're right. What I was doing was unnecessary, and should have been obvious if I added more context to the problem. I was storing `Url.Content("~")` in a javascript variable that I wanted to access, which is stupid considering I could have accessed it directly from the razor code. I'll mark yours as the answer, because you made me reconsider the scenario. Thanks. – Daniel Minnaar Aug 04 '15 at 11:00
0

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>
bencrinkle
  • 278
  • 4
  • 13