Reputation: 6315
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?
Upvotes: 0
Views: 152
Reputation: 298
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>
Upvotes: 0
Reputation: 5008
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 :)
Upvotes: 1