ASP.Net MVC: How to use razor variable in CSS file

2019-06-08 05:23发布

问题:

as per my scenario i need to store this path /img/product.png of image in razor variable and later i want to use that razor variable in CSS file. below css code is in css file

.test{
    background: url('/img/product.png') no-repeat scroll 0 0 transparent;
}

so i use code like this way below but no luck still

.test{
    background: url('@Model.LogoUrl') no-repeat scroll 0 0 transparent;
}

i see this post http://www.codeproject.com/Articles/171695/Dynamic-CSS-using-Razor-Engine but i do not want to solve my issue as per the post. so let me know how to sort this issue. thanks

回答1:

By default, MVC does not support writing server side codes in external CSS file and external Javascript files.

For your case to work, you can add an internal stylesheet in your view file itself, it will work.

Eg:

@{
    ViewBag.Title = "Title";
}
<style>
    .test {
        background: url('@Model.LogoUrl') no-repeat scroll 0 0 transparent;
    }  
</style>


回答2:

As far as I know, you cannot refer or write Razor code in a CSS file. CSS files are processed by the browser where as the Razor code is executed by the server and then rendered by the browser

For your problem, you will need to write an inline style



回答3:

You can also do it in HTML part like this:

For example:

<div class="test" style="background: url(..@Model.LogoUrl) no-repeat scroll 0 0 transparent;">
...
</div>