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

2019-06-08 05:18发布

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

3条回答
Animai°情兽
2楼-- · 2019-06-08 05:45

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楼-- · 2019-06-08 05:47

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>
查看更多
闹够了就滚
4楼-- · 2019-06-08 05:47

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>
查看更多
登录 后发表回答