从 html 助手中获取未编码的 html

Getting unencoded html out of html helper

多年来,对此有很多答案,在有人对我大喊大叫之前,我已经尝试了所有答案,但就是无法工作。我正在使用 MVC 5、Razor 3、Visual Studio 2017。这是一个简化的测试:

在我的 App_Code 文件夹中,我有一个 SSLhelpers.cshtml 文件,其中包含:

@helper Macro(string Htext, string Ptext)
{
    <h2>@Htext</h2>
    <p>@Ptext</p>
}

在我看来我有:

@SSLhelpers.Macro("This is my header", "This is my paragraph text. We should 
be <strong>bold</strong> here but we're not.")

生成的html为:

<h2>This is my header</h2>

<p>This is my paragraph text. We should be &lt;strong&gt;bold&lt;/strong&gt; 
here but we're not.</p>

如何避免编码?

谢谢。

您可以这样使用 HtmlString

@helper Macro(string Htext, string Ptext)
{
    <h2>@(new HtmlString(Htext))</h2>
    <p>@(new HtmlString(Ptext))</p>
}

创建自定义助手(视图中引用的命名空间):

    public static HtmlString TestHtmlString(this HtmlHelper html, string hText, string pText)
    {
        var h = new TagBuilder("h2");
        var p = new TagBuilder("p");
        h.InnerHtml = hText;
        p.InnerHtml = pText;
        return new HtmlString(h.ToString(TagRenderMode.Normal) + p.ToString(TagRenderMode.Normal));
    }

然后您可以在您的视图中使用它:

@Html.TestHtmlString("This is my header", "This is my paragraph text. We should be <strong> bold </strong> here but we're not.")