【问题标题】:Getting unencoded html out of html helper从 html 帮助程序中获取未编码的 html
【发布时间】:2023-03-26 11:22:01
【问题描述】:

多年来,对此有很多答案,在有人对我大喊大叫之前,我已经尝试了所有方法,但无法正常工作。我正在使用 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>

如何避免编码?

谢谢。

【问题讨论】:

    标签: c# asp.net asp.net-mvc razor razorengine


    【解决方案1】:

    你可以像这样使用HtmlString

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2013-03-21
        • 2015-02-05
        • 1970-01-01
        • 2014-06-04
        • 2011-12-28
        • 2014-12-06
        • 1970-01-01
        • 2010-11-29
        • 2015-09-08
        相关资源
        最近更新 更多