如何使用转义字符为Razor编写动态内部CSS?

huangapple go评论92阅读模式
英文:

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')}" })

这种方法的问题在于我遇到了转义字符&#39;\n的问题,并且得到了.someClass{background: url(&amp;#x27;urlToMyImage&amp;#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(&quot;\n\n&quot;, new List&lt;string&gt; { &quot;.someClass{background: url(&#39;urlToMyImage&#39;)}&quot; })

The problem with this approach is that I am having problems escaping the characters &#39; and \n. and I am getting .someClass{background: url(&amp;#x27;urlToMyImage&amp;#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(&quot;\n\n&quot;, new List&lt;string&gt; { &quot;.someClass{background: url(&#39;urlToMyImage&#39;)}&quot; }))

As will the somewhat longer:

@{
     string output;

     output = string.Join(&quot;\n\n&quot;, new List&lt;string&gt; { &quot;.someClass{background: url(&#39;urlToMyImage&#39;)}&quot; });
     @Html.Raw(output);
 }

huangapple
  • 本文由 发表于 2020年1月6日 18:48:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/59610733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定