在 ASP.NET C# 和 Razor 中的变量内编写 HTML 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12964161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing HTML code inside variable in ASP.NET C# and Razor
提问by Carasuman
I'm new in ASP.NET C# and I have problems with some things.
我是 ASP.NET C# 的新手,我遇到了一些问题。
In PHP, I can store HTML code inside a variable, for example:
在 PHP 中,我可以将 HTML 代码存储在一个变量中,例如:
$list = "<li>My List</li>";
echo "<ul>{$list}</ul>"; // write <ul><li>My List</li></ul>
I tried this in ASP.NET and Razor
我在 ASP.NET 和 Razor 中试过这个
string List = "<li>My List</li>";
<ul>@List</ul>
But ASP changes "<" and ">" to >and <.. You know any solution for this?
但是 ASP 将 "<" 和 ">" 更改为>and <.. 你知道有什么解决方案吗?
I have another question, can I insert variable inside a quotes like PHP?
我还有一个问题,我可以在像 PHP 这样的引号中插入变量吗?
echo "<ul>{$list}</ul>";
采纳答案by McGarnagle
The Razor engine HTML encodes strings by default, as you have noticed. To avoid this behavior, just use Html.Raw():
正如您所注意到的,Razor 引擎 HTML 默认对字符串进行编码。为避免这种行为,只需使用Html.Raw():
<ul>@Html.Raw(List)</ul>
Edit
编辑
To render a variable within a string, I suppose you could use string.Format:
要呈现字符串中的变量,我想您可以使用string.Format:
@{ var someVariable = "world"; }
@string.Format("<div>hello {0}</div>", someVariable)
Although that seems like overkill (at least for this example) when you can just write:
虽然这看起来有点矫枉过正(至少在这个例子中),当你可以写的时候:
<div>hello @someVariable</div>

