英文:
How to write dynamic internal css with escaped characters for razor?
问题
我正在尝试在Razor中添加动态内部CSS。我无法使用外部文件。我想在我的cshtml文件的head元素中添加一些CSS。
例如:我想为某些元素添加一些背景图片。我正在添加我尝试过的简化代码。在实际情况下,列表类和URL将是动态的。
@string.Join("\n\n", new List<string> { ".someClass{background: url('urlToMyImage')}" })
这种方法的问题在于我遇到了转义字符'
和\n
的问题,并且得到了.someClass{background: url(&#x27;urlToMyImage&#x27;)}
。
我还尝试过使用@Html.Raw
,但没有成功。
英文:
I am trying to add dynamic internal css in razor. I CANNOT use external files. I want to add some css in the head element of my cshtml file.
For example: I want to add some background images to some elements.
I am adding this simplified code of what I have tried. In the real case the List classes and urls would be dynamic.
@string.Join("\n\n", new List<string> { ".someClass{background: url('urlToMyImage')}" })
The problem with this approach is that I am having problems escaping the characters '
and \n
. and I am getting .someClass{background: url(&#x27;urlToMyImage&#x27;)}
I also tried using @Html.Raw
but without success.
答案1
得分: 0
你之前考虑使用@Html.Raw
是正确的。我不确定你是如何实现的,但以下方法可以正常工作:
@Html.Raw(string.Join("\n\n", new List<string> { ".someClass{background: url('urlToMyImage')}" }))
另一种稍微冗长的方式也可以:
@{
string output;
output = string.Join("\n\n", new List<string> { ".someClass{background: url('urlToMyImage')}" });
@Html.Raw(output);
}
英文:
You were thinking along the right lines with @Html.Raw
. I'm not sure how you implemented it, but this will work:
@Html.Raw(string.Join("\n\n", new List<string> { ".someClass{background: url('urlToMyImage')}" }))
As will the somewhat longer:
@{
string output;
output = string.Join("\n\n", new List<string> { ".someClass{background: url('urlToMyImage')}" });
@Html.Raw(output);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论