【问题标题】:Print inner text of a HtmlContent in a razor view (MVC4)在剃刀视图(MVC4)中打印 HtmlContent 的内部文本
【发布时间】:2013-05-02 19:02:54
【问题描述】:

使用 MVC,看看这个例子,我们有以下 HTML 代码:

<p>Duma</p><img url='..' /><p>Duma</p>

我希望只打印标签的内容,如:Duma Duma,删除图像、标签并仅显示文本(作为 innerText)

我尝试使用 Html.Raw() 但它不起作用。我也在阅读 TabBuilder 类并创建一个 Html 扩展方法,但我不知道如何在我的剃刀视图中实现。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 tagbuilder


    【解决方案1】:

    你可以做一个字符串扩展来去除 Html 标签。

    public static class StringExtensions
    {
        public static string StripHtml (this string inputString)
        {
           return Regex.Replace 
             (inputString, "<.*?>", string.Empty);
        }
    }
    

    然后在你的视图中使用它

    @myHtmlString.StripHtml()
    

    您可能需要为 StringExtensions 类声明 using 语句或将其添加到 Views 文件夹中的 Web.Config 文件中

    @using My.Extensions.Namespace
    

    <system.web>
        <pages>
          <namespaces>
            <add namespace="My.Extensions.Namespace" />
          </namespaces>
        </pages>
    </system.web>
    

    你也可以做一个 Html Helper Extension

    public static class HtmlExtensions
    {
        public static string StripHtml (this System.Web.Mvc.HtmlHelper helper, string htmlString)
        {
           return Regex.Replace 
             (htmlString, "<.*?>", string.Empty);
        }
    }
    

    你可以像这样在你的视图中使用它

    @Html.StripHtml(myHtmlString)
    

    您仍然需要为上述扩展方法添加对命名空间的引用。在 Views 文件夹中添加到 Web.Config 或在视图中添加 using 语句。这里的不同之处在于,将其添加到您的 Web.Config 文件中,您将能够在所有视图中使用此扩展方法,而无需添加 using 语句。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      相关资源
      最近更新 更多