代码之家  ›  专栏  ›  技术社区  ›  user2250708

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

  •  1
  • user2250708  · 技术社区  · 6 年前

    多年来有很多答案,在有人对我大喊大叫之前,我已经试过了,但都没用。我使用的是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>
    

    如何避免编码?

    非常感谢。

    2 回复  |  直到 6 年前
        1
  •  2
  •   Evk    6 年前

    你可以用 HtmlString 这样地:

    @helper Macro(string Htext, string Ptext)
    {
        <h2>@(new HtmlString(Htext))</h2>
        <p>@(new HtmlString(Ptext))</p>
    }
    
        2
  •  1
  •   RickL    6 年前

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

        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.")